package com.ruoyi.gd.ywdwgd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.amazonaws.util.IOUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.gd.fj.domain.bo.ZFujianBo;
import com.ruoyi.gd.fj.domain.vo.ZFujianVo;
import com.ruoyi.gd.fj.service.IZFujianService;
import com.ruoyi.gd.wgd.domain.bo.ZWgdBo;
import com.ruoyi.gd.wgd.domain.vo.ZWgdVo;
import com.ruoyi.gd.wgd.service.IZWgdService;
import com.ruoyi.gd.wgd.service.impl.ZWgdServiceImpl;
import com.ruoyi.gd.xcaplog.domain.ZXcapLog;
import com.ruoyi.gd.xcaplog.mapper.ZXcapLogMapper;
import com.ruoyi.gd.xcaplog.service.IZXcapLogService;
import com.ruoyi.gd.ywd.domain.bo.ZYwdBo;
import com.ruoyi.gd.ywd.domain.vo.ZYwdVo;
import com.ruoyi.gd.ywd.service.IZYwdService;
import com.ruoyi.gd.ywdwgd.domain.vo.ReadExcelVo;
import com.ruoyi.gd.ywdwgd.domain.vo.ZYwdwgdKfpVo;
import com.ruoyi.gd.ywdwgd.utils.EasyExcelReadListener;
import com.ruoyi.gd.ywdwgdHistory.domain.ZYwdwgdHistory;
import com.ruoyi.gd.ywdwgdHistory.service.IZYwdwgdHistoryService;
import com.ruoyi.gd.ywdwgdLog.domain.ZYwdwgdLog;
import com.ruoyi.gd.ywdwgdLog.service.IZYwdwgdLogService;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.RequiredArgsConstructor;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.gd.ywdwgd.domain.bo.ZYwdwgdBo;
import com.ruoyi.gd.ywdwgd.domain.vo.ZYwdwgdVo;
import com.ruoyi.gd.ywdwgd.domain.ZYwdwgd;
import com.ruoyi.gd.ywdwgd.mapper.ZYwdwgdMapper;
import com.ruoyi.gd.ywdwgd.service.IZYwdwgdService;

import javax.annotation.Resource;
import java.io.*;
import java.lang.reflect.Field;
import java.math.BigInteger;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务完工单Service业务层处理
 *
 * @author ruoyi
 * @date 2024-08-01
 */
@RequiredArgsConstructor
@Service
public class ZYwdwgdServiceImpl implements IZYwdwgdService {

    private final ZYwdwgdMapper baseMapper;

    @Resource
    private ZXcapLogMapper zcapLogMapper;

    @Resource
    private IZYwdService zywgdService;

    @Resource
    private IZWgdService wgdService;

    @Resource
    private IZXcapLogService xzcapLogService;

    @Resource
    private ISysDictTypeService dictTypeService;

    @Resource
    private IZFujianService fujianService;

    @Resource
    private IZYwdwgdLogService zywgdLogService;

    @Resource
    private IZYwdwgdHistoryService zyhHistoryService;

    @Value("${upload.path}")
    private String uploadPath;

    @Value("${upload.kfp}")
    private String kfpPath;

    /**
     * 查询业务完工单
     */
    @Override
    public ZYwdwgdVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询业务完工单列表
     */
    @Override
    public TableDataInfo<ZYwdwgdVo> queryPageList(ZYwdwgdBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ZYwdwgd> lqw = buildQueryWrapper(bo);
        Page<ZYwdwgdVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询业务完工单列表
     */
    @Override
    public List<ZYwdwgdVo> queryList(ZYwdwgdBo bo) {
        LambdaQueryWrapper<ZYwdwgd> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public List<ZYwdwgdVo> queryListByIds(String ids) {
        return baseMapper.queryListByIds(ids.split(","));
    }

    @Override
    public List<ZYwdwgdVo> queryAllList(ZYwdwgdBo bo) {
        return baseMapper.queryAllList();
    }

    @Override
    public int handleZt(String id, String type) {
        int row = baseMapper.handleZt(id.split(","), type);
        return row;
    }

    @Override
    public boolean verifyBh(String bh) {
        List<ZYwdwgdVo> list = baseMapper.verifyBh(bh);
        return list.size() > 0;
    }

    /**
     * 生成报价单
     * 逻辑：
     * 1.获取当前的完工单，将完工单的列表数据进行解析为List
     * 2.将解析的List数据基于模板插入到报价单模板中
     * 3.将生成的报价单的流返回给前端
     */
    @Override
    public ZFujianBo genBjd(ZYwdwgdBo bo) {
        // 通过当前的附件id获取当前的附件
        if (StringUtils.isNotEmpty(bo.getWgdfj())) {
            List<ZFujianVo> zFujianVos = fujianService.queryListByIdOrdery(bo.getWgdfj());
            for (ZFujianVo zFujianVo : zFujianVos) {
                String fjpath = uploadPath + zFujianVo.getFjpath();

                FileInputStream fis = null;
                FileOutputStream fos = null;
                FileInputStream fileInputStream = null;
                FileOutputStream fileOutputStream = null;
                try  {
                    fis = new FileInputStream(fjpath);
                    ZipSecureFile.setMinInflateRatio(0.0);
                    Workbook workbook = new XSSFWorkbook(fis);
                    Sheet sheet = workbook.getSheetAt(0); // 假设我们要操作第一个sheet
                    JSONObject jsonData = getDatas(sheet, sheet.getLastRowNum());
                    JSONArray wgdList = new JSONArray();
                    for (int row = 0; row <= sheet.getLastRowNum(); row++) {
                        // 获取一行数据
                        Row cells = sheet.getRow(row);
                        Integer slRow = jsonData.getInt("sl_row");
                        if (row > slRow) {
                            Integer slColumn = jsonData.getInt("sl_column");
                            Integer djColumn = jsonData.getInt("dj_column");
                            Cell bh = cells.getCell(jsonData.getInt("xh_column"));  // 编号
                            Cell yqmc = cells.getCell(jsonData.getInt("yqmc_column"));  // 仪器名称
                            Cell xh = cells.getCell(jsonData.getInt("xhgg_column"));  // 型号规格
                            Object zzcColumn = jsonData.getObj("zzc_column");
                            Cell zzc = null;
                            if (zzcColumn != null) {
                                zzc  = cells.getCell( (int) zzcColumn);  // 制造厂
                            }
                            Object ccbhColumn = jsonData.getObj("ccbh_column");
                            Cell ccbh = null;
                            if (ccbhColumn != null) {
                                ccbh  = cells.getCell( (int) ccbhColumn);  // 出厂编号
                            }
                            Object glbhColumn = jsonData.getObj("glbh_column");
                            Cell glbh = null;
                            if (glbhColumn != null) {
                                glbh  = cells.getCell( (int) glbhColumn);  // 管理编号
                            }
                            Cell sl = cells.getCell(slColumn);    // 数量
                            Cell dj = cells.getCell(djColumn);    // 单价

                            Object xjColumn = jsonData.getObj("xj_column");
                            Cell xj = null;
                            if (xjColumn != null) {
                                xj  = cells.getCell( (int) xjColumn);  // 管理编号
                            }

                            Object fwfsColumn = jsonData.getObj("fwfs_column");
                            Cell fwfs = null;
                            if (fwfsColumn != null) {
                                fwfs  = cells.getCell( (int) fwfsColumn);  // 管理编号
                            }

                            Object bzColumn = jsonData.getObj("bz_column");
                            Cell bz = null;
                            if (bzColumn != null) {
                                bz  = cells.getCell( (int) bzColumn);  // 管理编号
                            }

//                            Cell xj = cells.getCell(jsonData.getInt("xj_column"));    // 小计
//                            Cell fwfs = cells.getCell(jsonData.getInt("fwfs_column"));    // 服务方式
//                            Cell bz = cells.getCell(jsonData.getInt("bz_column"));    // 备注
                            if (bh != null && (bh.toString().contains("校准总费用")
                                || bh.toString().contains("现场服务费"))) {
                                JSONObject object = new JSONObject();
                                object.set("bh", row + 1);
                                object.set("yqmc", bh.toString());
                                object.set("xj", xj.toString());
                                wgdList.add(object);
                            } else if(bh != null && (bh.toString().contains("含6%专用增值税发票"))) {
//                                JSONObject object = new JSONObject();
//                                object.set("bh", row + 1);
//                                object.set("yqmc", bh.toString());
//                                object.set("xj", xj.toString());
//                                wgdList.add(object);
                                break;
                            } else if (bh != null && StringUtils.isNotEmpty(bh.toString())     // 编号
                                && yqmc != null && StringUtils.isNotEmpty(yqmc.toString())  // 仪器名称
                                && xh != null && StringUtils.isNotEmpty(xh.toString())      // 型号
                                && dj != null && StringUtils.isNotEmpty(dj.toString())    // 制造厂
                               ) {  // 出厂编号
                                JSONObject object = new JSONObject();
                                object.set("bh", bh != null ? bh.toString() : "");
                                object.set("yqmc", yqmc != null ? yqmc.toString() : "");
                                object.set("xh", xh != null ? xh.toString() : "");
                                object.set("zzc", zzc != null ? zzc.toString() : "");
                                object.set("ccbh", ccbh != null ? ccbh.toString() : "");
                                object.set("glbh", glbh != null ? glbh.toString() : "");
                                // 设置数量
                                Double slNum = 0.0;
                                if (sl != null) {
                                    slNum = Double.parseDouble(sl.toString());
                                }
                                object.set("sl", slNum);
                                // 设置单价
                                Double djNum = 0.0;
                                if (dj != null) {
                                    djNum = Double.parseDouble(dj.toString());
                                }
                                object.set("dj", djNum);
                                String sjZm = new CellReference(slRow, slColumn, false, false).formatAsString();
                                String djZm = new CellReference(slRow, djColumn, false, false).formatAsString();
                                String gs = sjZm + "*" + djZm;
                                object.set("xj", gs);
                                object.set("fwfs", fwfs.toString());
                                object.set("bz", bz.toString());
                                wgdList.add(object);
                            }
                        }
                    }

                    // 将JSONArray转换为List
                    List<Object> list = new ArrayList<>(wgdList);
                    // 交换最后两个元素
                    if (list.size() > 1) {
                        Collections.swap(list, list.size() - 1, list.size() - 2);
                    }

                    // 将List转换回JSONArray
                    wgdList = new JSONArray(list);

                    // 获取模板的路径
                    String excelUrl = getTemplatePath("template/bjdmb_20241103.xlsx");
                    fileInputStream = new FileInputStream(excelUrl);
                    Workbook fileWorkbook = new XSSFWorkbook(fileInputStream);
                    Sheet sheetData = fileWorkbook.getSheetAt(0);
                    // 在第二行，第一列添加委托单位  row 1 column 0
                    sheetData.getRow(2).getCell(0).setCellValue("委托单位（甲方）："+ bo.getKhname());
                    // 在第五行，第一列添加地址  row 4 column 0
                    sheetData.getRow(5).getCell(0).setCellValue("地  址："+bo.getKhdz());
                    // 在第三十行，第五列添加日期 row 29 column 4
                    SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
                    sheetData.getRow(25).getCell(4).setCellValue("日期："+ format.format(bo.getBjrq()));

                    if (list.size() > 0) {
                        // 在第7行（索引为6）前插入新行，将第7行及之后的行下移
                        sheetData.shiftRows(7, sheetData.getLastRowNum(), wgdList.size());
                    }

                    Font font = fileWorkbook.createFont();
                    font.setFontName("SimSun");  // 设置字体为宋体
                    // 创建单元格样式
                    CellStyle style = fileWorkbook.createCellStyle();
                    // 将字体应用到单元格样式
                    style.setFont(font);
                    // 设置单元格文字居中
                    style.setAlignment(HorizontalAlignment.CENTER);
                    style.setVerticalAlignment(VerticalAlignment.CENTER);
                    // 设置单元格的四边边框
                    style.setBorderTop(BorderStyle.THIN);
                    style.setBorderBottom(BorderStyle.THIN);
                    style.setBorderLeft(BorderStyle.THIN);
                    style.setBorderRight(BorderStyle.THIN);

                    List<Integer> jshArr = new ArrayList<>();
                    List<Integer> jshSumArr = new ArrayList<>();

                    int num = 0;
                    // 插入填充数据
                    for (int i = 0; i < wgdList.size(); i++) {
                        num++;
                        Integer currentRow = 7+i;
                        // 填充数据
                        JSONObject jsonObject = wgdList.getJSONObject(i);
                        if (jsonObject.getStr("yqmc").contains("校准总费用")) {
                            String val = "SUM(G"+jshArr.get(0)+":G"+jshArr.get(jshArr.size()-1)+")";
                            Row newRow = sheetData.createRow(currentRow);  // 当前行
                            Cell zero = newRow.createCell(0);   // 序号
                            Cell one = newRow.createCell(1);    // 仪器名称
                            Cell six = newRow.createCell(6);   // 小计
                            // 设置值
//                            zero.setCellValue(jsonObject.getStr("bh"));
                            zero.setCellValue(num);
//                            one.setCellValue(jsonObject.getStr("yqmc"));
                            one.setCellValue("合计金额");
                            six.setCellFormula(val);
                            // 设置样式
                            zero.setCellStyle(style);
                            one.setCellStyle(style);
                            six.setCellStyle(style);
                            newRow.createCell(2).setCellStyle(style);
                            newRow.createCell(3).setCellStyle(style);
                            newRow.createCell(4).setCellStyle(style);
                            newRow.createCell(5).setCellStyle(style);
                            newRow.createCell(7).setCellStyle(style);
                            newRow.createCell(8).setCellStyle(style);
                            newRow.setHeightInPoints(25);
                            jshSumArr.add(setZfy(currentRow));
                            break;
                        }else {
                            // 当前是填充数据
                            Row newRow = sheetData.createRow(currentRow);  // 当前行
                            Cell zero = newRow.createCell(0);   // 序号
                            Cell one = newRow.createCell(1);    // 仪器名称
                            Cell two = newRow.createCell(2);    // 型号规格
                            Cell three = newRow.createCell(3);  // 编号
                            Cell four = newRow.createCell(4);   // 单价
                            Cell five = newRow.createCell(5);   // 数量
                            Cell six = newRow.createCell(6);   // 小计
                            Cell seven = newRow.createCell(7);   // 服务方式
                            Cell eight = newRow.createCell(8);   // 备注
                            // 每一行设置样式
//                            zero.setCellValue(jsonObject.getStr("bh"));
                            zero.setCellValue(num);
                            one.setCellValue(jsonObject.getStr("yqmc"));
                            two.setCellValue(jsonObject.getStr("xh"));
                            // 判断当前报价单的编号使用完工单的哪个编号
                            if (StringUtils.isNotEmpty(bo.getBjdh()) && "ccbh".equals(bo.getBjdh())) {
                                three.setCellValue(jsonObject.getStr("ccbh"));
                            }else if (StringUtils.isNotEmpty(bo.getBjdh()) && "glbh".equals(bo.getBjdh())) {
                                three.setCellValue(jsonObject.getStr("glbh"));
                            }
                            if(jsonObject.getStr("yqmc").contains("现场服务费")) {
                                // 设置仪器名称
                                one.setCellValue("下场费");
                                four.setCellValue("");
                                five.setCellValue("");
                                Double xj = jsonObject.getDouble("xj");
                                six.setCellValue(xj != null ? xj : 0);
                                jshSumArr.add(setZfy(currentRow));
                            }else {
                                Double dj = jsonObject.getDouble("dj");
                                four.setCellValue(dj != null ? dj : 0);
                                Double sl = jsonObject.getDouble("sl");
                                five.setCellValue(sl != null ? sl : 0);
                                String sjZm = new CellReference(currentRow, 4, false, false).formatAsString();
                                String djZm = new CellReference(currentRow, 5, false, false).formatAsString();
                                six.setCellFormula(sjZm + "*" + djZm);
                            }
                            seven.setCellValue(jsonObject.getStr("fwfs"));
                            eight.setCellValue(jsonObject.getStr("bz"));
                            // 先设置单元格演示
                            zero.setCellStyle(style);
                            one.setCellStyle(style);
                            two.setCellStyle(style);
                            three.setCellStyle(style);
                            four.setCellStyle(style);
                            five.setCellStyle(style);
                            six.setCellStyle(style);
                            seven.setCellStyle(style);
                            eight.setCellStyle(style);
                            // 设置计算列
                            jshArr.add(setZfy(currentRow));
                            newRow.setHeightInPoints(25);
                        }
                    }
                    // ==================== 生成图片  ================
                    // 获取行和列
                    int lastRowNum = sheetData.getLastRowNum();
                    int rowIndex = lastRowNum - 8; // 倒数第10行
                    int columnIndex = 6; // 第2列
                    for (int row = 0; row <= sheetData.getLastRowNum(); row++){
                        Row rowData = sheetData.getRow(row);
                        if (rowData != null) {
                            Cell cell = rowData.getCell(0);
                            if (cell != null && StringUtils.isNotEmpty(cell.toString()) && cell.toString().contains("（11）")) {
                                rowIndex = rowData.getRowNum();
                                break;
                            }
                        }
                    }
                    // 创建一个绘图对象
                    Drawing<?> drawing = sheetData.createDrawingPatriarch();
                    ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, columnIndex, rowIndex, columnIndex + 3, rowIndex + 13);
                    // 获取图片路径
                    String imgUrl = getTemplatePath("template/dafeng.png");
                    // 添加图片
                    byte[] imageBytes = getImageBytes(imgUrl);
                    int pictureIndex = fileWorkbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
                    Picture picture = drawing.createPicture(anchor, pictureIndex);
                    picture.resize(0.6);
                    // ==================== 生成图片  ================

                    // 获取当前下载excel的路径
                    LocalDate currentDate = LocalDate.now();
                    // 分别获取年、月、日
                    int year = currentDate.getYear();
                    int monthValue = currentDate.getMonthValue();
                    int dayOfMonth = currentDate.getDayOfMonth();
                    // 生成Excel路径
                    String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/" + "wgdToBjd/";
                    // 判断当前文件路径的文件夹是否存在，不存在则创建
                    if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
                        // 路径不存在，尝试创建
                        try {
                            Files.createDirectories(Paths.get(uploadPath + suffixPath));
                        } catch (Exception e) {
                            System.err.println("创建目录时出错: " + e.getMessage());
                        }
                    }
                    // 报价单名称 日期+报价单+单位名称
                    String rq = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                    String fileName = year + monthValue + dayOfMonth + "报价单" + bo.getKhname()+"_"+ rq + ".xlsx";
                    String path = uploadPath + suffixPath + fileName;
                    fileOutputStream = new FileOutputStream(path);
                    fileWorkbook.write(fileOutputStream);
                    fileWorkbook.close();
                    // 将当前的文件保存到附件表中
                    ZFujianBo fujian = new ZFujianBo();
                    fujian.setFjid(IdUtil.simpleUUID());  //设置附件id
                    fujian.setFjname(fileName);   //设置附件名称
                    fujian.setFjpath(suffixPath + fileName);  //设置附件路径
                    fujian.setFjtype(".xlsx");
                    fujianService.insertByBo(fujian);

                    // 查询当前的完工单数据
                    ZYwdwgd zYwdwgd = baseMapper.selectById(bo.getId());
                    String lsbjdid = zYwdwgd.getLsbjdid();
                    if (StringUtils.isNotEmpty(lsbjdid)) {
                        lsbjdid += fujian.getFjid() + ",";
                    }else {
                        lsbjdid = fujian.getFjid() + ",";
                    }
                    // 修改当前的报价单历史报价单id
                    zYwdwgd.setLsbjdid(lsbjdid);
                    baseMapper.updateById(zYwdwgd);
                    return fujian;
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fileInputStream != null) {
                        try {
                            fileInputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    /**
     * 生成报价单数据
     * @param bo
     * @return
     */
    @Override
    public byte[] genBjdData(ZFujianBo bo) {
        if (StringUtils.isNotEmpty(bo.getFjid())) {
            List<ZFujianVo> zFujianVos = fujianService.queryListByIdOrdery(bo.getFjid());
            for (ZFujianVo zFujianVo : zFujianVos) {
                String fjpath = uploadPath + zFujianVo.getFjpath();
                FileInputStream fis = null;
                FileOutputStream fos = null;
                try  {
                    fis = new FileInputStream(fjpath);
                    Workbook workbook = new XSSFWorkbook(fis);
                    Sheet sheet = workbook.getSheetAt(0); // 假设我们要操作第一个sheet
                    JSONArray array = new JSONArray();
                    for (int i = 7; i <= sheet.getLastRowNum(); i++) {
                        Row row = sheet.getRow(i);
                        if (row.getCell(0) !=null && StringUtils.isNotEmpty(row.getCell(0).toString())
                            && row.getCell(1) !=null && StringUtils.isNotEmpty(row.getCell(1).toString())
                            && row.getCell(2) !=null && StringUtils.isNotEmpty(row.getCell(2).toString())
                            && row.getCell(4) !=null && StringUtils.isNotEmpty(row.getCell(4).toString())
                            && row.getCell(5) !=null && StringUtils.isNotEmpty(row.getCell(5).toString())) {
                            JSONObject object = new JSONObject();
                            object.set("bh", row.getCell(0) !=null ? row.getCell(0).toString() : "");
                            object.set("yqmc", row.getCell(1) !=null ? row.getCell(1).toString() : "");
                            object.set("ggxh", row.getCell(2) !=null ? row.getCell(2).toString() : "");
                            object.set("glbh", row.getCell(3) !=null ? row.getCell(3).toString() : "");
                            object.set("dj", row.getCell(4) !=null ? Double.parseDouble(row.getCell(4).toString()) : "");
                            object.set("sl", row.getCell(5) !=null ? Double.parseDouble(row.getCell(5).toString()) : "");
                            object.set("xj", row.getCell(6) !=null ? row.getCell(6).getNumericCellValue() : "");
                            object.set("fwfs", row.getCell(7) !=null ? row.getCell(7).toString() : "");
                            object.set("bz", row.getCell(8) !=null ? row.getCell(8).toString() : "");
                            array.add(object);
                        }else if (row.getCell(1) != null
                            && StringUtils.isNotEmpty(row.getCell(1).toString())
                            && (row.getCell(1).toString().contains("校准总费用")
                            || row.getCell(1).toString().contains("现场服务费")
                            || row.getCell(1).toString().contains("含6%专用增值税发票"))
                        ) {
                            JSONObject object = new JSONObject();
                            object.set("bh", row.getCell(0) !=null ? row.getCell(0).toString() : "");
                            object.set("yqmc", row.getCell(1) !=null ? row.getCell(1).toString() : "");
                            object.set("ggxh", row.getCell(2) !=null ? row.getCell(2).toString() : "");
                            object.set("glbh", row.getCell(3) !=null ? row.getCell(3).toString() : "");
                            Cell four = row.getCell(4);
                            if (four != null && StringUtils.isNotEmpty(four.toString())) {
                                object.set("dj", Double.parseDouble(four.toString()));
                            }else {
                                object.set("dj", "");
                            }
                            Cell five = row.getCell(5);
                            if (five != null && StringUtils.isNotEmpty(five.toString())) {
                                object.set("sl", Double.parseDouble(five.toString()));
                            }else {
                                object.set("sl", "");
                            }
                            object.set("xj", row.getCell(6) !=null ? row.getCell(6).toString() : "");
                            object.set("fwfs", row.getCell(7) !=null ? row.getCell(7).toString() : "");
                            object.set("bz", row.getCell(8) !=null ? row.getCell(8).toString() : "");
                            array.add(object);
                        }
                    }
                    // 设置样式
                    // 获取当前报价单路径
                    String path = getBjdPath();
                    String fileName = "报价单" +
                        new SimpleDateFormat("yyyyMMdd").format(new Date()) +
                        "_"+ IdUtil.simpleUUID() + ".xlsx";
                    fos = new FileOutputStream(path + fileName);
                    // 创建工作簿
                    Workbook workData = new XSSFWorkbook();
                    Font font = workData.createFont();
                    font.setFontName("SimSun");  // 设置字体为宋体
                    // 创建单元格样式
                    CellStyle style = workData.createCellStyle();
                    // 将字体应用到单元格样式
                    style.setFont(font);
                    // 设置单元格文字居中
                    style.setAlignment(HorizontalAlignment.CENTER);
                    style.setVerticalAlignment(VerticalAlignment.CENTER);
                    // 设置单元格的四边边框
                    style.setBorderTop(BorderStyle.THIN);
                    style.setBorderBottom(BorderStyle.THIN);
                    style.setBorderLeft(BorderStyle.THIN);
                    style.setBorderRight(BorderStyle.THIN);
                    // 创建工作表
                    Sheet sheetData = workData.createSheet();
                    Row row = sheetData.createRow(0);
                    // 设置第一行数据
                    row.createCell(0).setCellValue("序号");  row.getCell(0).setCellStyle(style);
                    row.createCell(1).setCellValue("仪器名称"); row.getCell(1).setCellStyle(style);
                    row.createCell(2).setCellValue("型号规格"); row.getCell(2).setCellStyle(style);
                    row.createCell(3).setCellValue("管理编号"); row.getCell(3).setCellStyle(style);
                    row.createCell(4).setCellValue("单价（元）"); row.getCell(4).setCellStyle(style);
                    row.createCell(5).setCellValue("数量");      row.getCell(5).setCellStyle(style);
                    row.createCell(6).setCellValue("小计（元）"); row.getCell(6).setCellStyle(style);
                    row.createCell(7).setCellValue("服务方式"); row.getCell(7).setCellStyle(style);
                    row.createCell(8).setCellValue("备注");     row.getCell(8).setCellStyle(style);
                    sheetData.setColumnWidth(0, 20 * 256 + 400);
                    // 最后行
                    List<Integer> xjArr = new ArrayList<>();
                    List<Integer> sumArr = new ArrayList<>();
                    // 将内容写到Excel中
                    a:for (int i = 0; i < array.size(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        Row rowData = sheetData.createRow(i + 1);
                        sheetData.setColumnWidth(i + 1, 20 * 256 + 400);
                        rowData.createCell(0).setCellStyle(style);
                        rowData.createCell(1).setCellStyle(style);
                        rowData.createCell(2).setCellStyle(style);
                        rowData.createCell(3).setCellStyle(style);
                        rowData.createCell(4).setCellStyle(style);
                        rowData.createCell(5).setCellStyle(style);
                        rowData.createCell(6).setCellStyle(style);
                        rowData.createCell(7).setCellStyle(style);
                        rowData.createCell(8).setCellStyle(style);
                        rowData.setHeightInPoints(25);
                        String yqmc = jsonObject.getStr("yqmc");
                        if (StringUtils.isNotEmpty(yqmc)
                            && (yqmc.contains("校准总费用"))) {
                            String val = "SUM(G"+xjArr.get(0)+":G"+xjArr.get(xjArr.size()-1)+")";
                            rowData.getCell(0).setCellValue(jsonObject.getStr("bh"));
                            rowData.getCell(1).setCellValue("校准总费用：");  // 设置仪器名称
                            rowData.getCell(6).setCellFormula(val);
                            sumArr.add(setZfy(i + 1));
                        }else if (StringUtils.isNotEmpty(yqmc)
                            && (yqmc.contains("含6%专用增值税发票"))) {
                            String val = "SUM(G"+sumArr.get(sumArr.size()-2)+":G"+sumArr.get(sumArr.size()-1)+")";
                            rowData.getCell(0).setCellValue(jsonObject.getStr("bh"));
                            rowData.getCell(1).setCellValue("含6%专用增值税发票，合计总费用：");  // 设置仪器名称
                            rowData.getCell(6).setCellFormula(val);
                            break a;
                        }else if (StringUtils.isNotEmpty(yqmc)
                            && (yqmc.contains("现场服务费"))) {
                            rowData.getCell(0).setCellValue(jsonObject.getStr("bh"));
                            rowData.getCell(1).setCellValue(jsonObject.getStr("yqmc"));
                            rowData.getCell(2).setCellValue(jsonObject.getStr("ggxh"));
                            rowData.getCell(3).setCellValue(jsonObject.getStr("glbh"));
                            if (jsonObject.getDouble("dj") != null) {
                                rowData.getCell(4).setCellValue(jsonObject.getDouble("dj"));
                            }else {
                                rowData.getCell(4).setCellValue("");
                            }
                            if (jsonObject.getDouble("sl") != null) {
                                rowData.getCell(4).setCellValue(jsonObject.getDouble("sl"));
                            }else {
                                rowData.getCell(4).setCellValue("");
                            }
                            rowData.getCell(6).setCellValue(jsonObject.getDouble("xj") != null ? jsonObject.getDouble("xj") : 0);
                            rowData.getCell(7).setCellValue(jsonObject.getStr("fwfs"));
                            rowData.getCell(8).setCellValue(jsonObject.getStr("bz"));
                            sumArr.add(setZfy(i + 1));
                        }else {
                            rowData.getCell(0).setCellValue(jsonObject.getStr("bh"));
                            rowData.getCell(1).setCellValue(jsonObject.getStr("yqmc"));
                            rowData.getCell(2).setCellValue(jsonObject.getStr("ggxh"));
                            rowData.getCell(3).setCellValue(jsonObject.getStr("glbh"));
                            rowData.getCell(4).setCellValue(jsonObject.getDouble("dj") != null ? jsonObject.getDouble("dj") : 0);
                            rowData.getCell(5).setCellValue(jsonObject.getDouble("sl") != null ? jsonObject.getDouble("sl") : 0);
                            String sjZm = new CellReference(i + 1, 4, false, false).formatAsString();
                            String djZm = new CellReference(i + 1, 5, false, false).formatAsString();
                            Cell cell = rowData.getCell(6);
                            cell.setCellFormula(sjZm + "*" + djZm);
//                            rowData.getCell(6).setCellValue(jsonObject.getDouble("xj") != null ? jsonObject.getDouble("xj") : 0);
                            rowData.getCell(7).setCellValue(jsonObject.getStr("fwfs"));
                            rowData.getCell(8).setCellValue(jsonObject.getStr("bz"));
                            xjArr.add(setZfy(i + 1));
                            sumArr.add(setZfy(i + 1));
                        }
                    }
                    // 写入文件
                    workData.write(fos);
                    // 关闭资源
                    fis.close();
                    workData.close();
                    // 获取当前的文件流
                    FileInputStream inputStream = new FileInputStream(path + fileName);
                    byte[] bytes = IOUtils.toByteArray(inputStream);
                    inputStream.close();
                    return bytes;
                }catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return null;
    }

    public String getBjdPath() {
        // 获取当前下载excel的路径
        LocalDate currentDate = LocalDate.now();
        // 分别获取年、月、日
        int year = currentDate.getYear();
        int monthValue = currentDate.getMonthValue();
        int dayOfMonth = currentDate.getDayOfMonth();
        String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/" + "bjdData/";
        String path = uploadPath + suffixPath;
        // 判断当前文件路径的文件夹是否存在，不存在则创建
        if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
            // 路径不存在，尝试创建
            try {
                Files.createDirectories(Paths.get(uploadPath + suffixPath));
            } catch (Exception e) {
                System.err.println("创建目录时出错: " + e.getMessage());
                throw new RuntimeException("创建目录时出错");
            }
        }
        return path;
    }


    private JSONObject getDatas(Sheet sheet, int lastRowNum) {
        JSONObject jsonObject = new JSONObject();
        boolean xh = false; boolean yqmc = false; boolean xhgg = false; boolean zzc = false;
        boolean ccbh = false; boolean glbh = false; boolean sl = false; boolean dj = false; boolean xj = false;
        boolean fwfs = false; boolean bz = false;
        a:for (int i = 0; i < lastRowNum; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                for (int j = 0; j < row.getLastCellNum(); j++) {
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        String cellValue = cell.toString().trim();
                        if ("序号".equals(cellValue)  && !xh) { // 判断当前的序号位置
                            jsonObject.put("xh_row", i);
                            jsonObject.put("xh_column",j);
                            xh = true;
                        }else if ("仪器名称".equals(cellValue)  && !yqmc) { // 判断当前的仪器名称位置
                            jsonObject.put("yqmc_row", i);
                            jsonObject.put("yqmc_column", j);
                            yqmc = true;
                        }else if (("型号/规格".equals(cellValue) || "型号规格".equals(cellValue))  && !xhgg) { // 判断当前的型号/规格位置
                            jsonObject.put("xhgg_row", i);
                            jsonObject.put("xhgg_column", j);
                            xhgg = true;
                        }else if ("制造厂".equals(cellValue)  && !zzc) { // 判断当前的制造厂位置
                            jsonObject.put("zzc_row", i);
                            jsonObject.put("zzc_column", j);
                            zzc = true;
                        }else if ("出厂编号".equals(cellValue)  && !ccbh) { // 判断当前的出厂编号位置
                            jsonObject.put("ccbh_row", i);
                            jsonObject.put("ccbh_column", j);
                            ccbh = true;
                        }else if ("管理编号".equals(cellValue)  && !glbh) { // 判断当前的管理编号位置
                            jsonObject.put("glbh_row", i);
                            jsonObject.put("glbh_column", j);
                            glbh = true;
                        }else if ("数量".equals(cellValue)  && !sl) { // 判断当前的数量位置
                            jsonObject.put("sl_row", i);
                            jsonObject.put("sl_column", j);
                            sl = true;
                        }else if ("单价（元）".equals(cellValue)  && !dj) { // 判断当前的单价（元）位置
                            jsonObject.put("dj_row", i);
                            jsonObject.put("dj_column", j);
                            dj = true;
                        }else if ("小计（元)".equals(cellValue)  && !xj) { // 判断当前的小计（元)位置
                            jsonObject.put("xj_row", i);
                            jsonObject.put("xj_column", j);
                            xj = true;
                        }else if ("服务方式".equals(cellValue)  && !fwfs) { // 判断当前的服务方式位置
                            jsonObject.put("fwfs_row", i);
                            jsonObject.put("fwfs_column", j);
                            fwfs = true;
                        }else if ("备注".equals(cellValue)  && !bz) { // 判断当前的备注位置
                            jsonObject.put("bz_row", i);
                            jsonObject.put("bz_column", j);
                            bz = true;
                        }

                    }
                }
            }

        }
        return jsonObject;
    }

    private String getTemplatePath(String path) throws URISyntaxException {
        // 使用当前类的 Class 对象来获取资源
        ClassLoader classLoader = ZWgdServiceImpl.class.getClassLoader();
        // 使用 getResource 方法获取 test.xlsx 文件的 URL
//        URL resourceUrl = classLoader.getResource("template/bjdmb1.xlsx");
        URL resourceUrl = classLoader.getResource(path);
        if (resourceUrl == null) {
            System.out.println("Resource not found.");
            return null;
        }
        // 将 URL 转换为文件路径
        return Paths.get(resourceUrl.toURI()).toString();
    }

    // 设置当前的行
    private Integer setZfy(Integer currentRow) {
        Integer currentColumn = currentRow + 1;
        return currentColumn;
    }

    private static byte[] getImageBytes(String imagePath) throws IOException {
        try (FileInputStream fis = new FileInputStream(imagePath)) {
            byte[] bytes = new byte[fis.available()];
            fis.read(bytes);
            return bytes;
        }
    }


    private LambdaQueryWrapper<ZYwdwgd> buildQueryWrapper(ZYwdwgdBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZYwdwgd> lqw = Wrappers.lambdaQuery();
        StringUtils.trimEntityFields(bo);
        try {
            LoginUser loginUser = LoginHelper.getLoginUser();
            lqw.like(StringUtils.isNotBlank(bo.getBjdh()), ZYwdwgd::getBjdh, bo.getBjdh());
            lqw.like(StringUtils.isNotBlank(bo.getKhname()), ZYwdwgd::getKhname, bo.getKhname());
            lqw.eq(bo.getHtje() != null, ZYwdwgd::getHtje, bo.getHtje());
            lqw.like(StringUtils.isNotBlank(bo.getKhsh()), ZYwdwgd::getKhsh, bo.getKhsh());
            lqw.like(StringUtils.isNotBlank(bo.getWgdh()), ZYwdwgd::getWgdh, bo.getWgdh());
            lqw.eq(bo.getZjfs() != null, ZYwdwgd::getZjfs, bo.getZjfs());
            lqw.like(StringUtils.isNotBlank(bo.getXcfzr()), ZYwdwgd::getXcfzr, bo.getXcfzr());
            lqw.like(StringUtils.isNotBlank(bo.getXcfzrname()), ZYwdwgd::getXcfzrname, bo.getXcfzrname());
            lqw.like(StringUtils.isNotBlank(bo.getXcry()), ZYwdwgd::getXcry, bo.getXcry());
            lqw.like(StringUtils.isNotBlank(bo.getXclx()), ZYwdwgd::getXclx, bo.getXclx());
            lqw.eq(bo.getKpje() != null, ZYwdwgd::getKpje, bo.getKpje());
            lqw.like(StringUtils.isNotBlank(bo.getFph()), ZYwdwgd::getFph, bo.getFph());
            lqw.like(StringUtils.isNotBlank(bo.getBz()), ZYwdwgd::getBz, bo.getBz());
            // 如果当前的完工单附件不为空，则完工单附件为 isNotNull 判断当前的完工单附件不为空
            if (StringUtils.isNotEmpty(bo.getWgdfj()) && "isNull".equals(bo.getWgdfj())) {
                lqw.isNull(ZYwdwgd::getWgdfj);
            }
            // 1.通过字典数据，哪些用户可以获取所有数据
            List<String> khGetAllData = dictTypeService.selectDictDataByType("kh_getAllData").stream().map(SysDictData::getDictValue).collect(Collectors.toList());
            // 判断字典数据中的id在集合中是否存在
            boolean b = khGetAllData.stream().anyMatch(val -> val.equals(loginUser.getUserId().toString()));
            // 如果当前用户不存在则查询所有
            if (!b) {
                lqw.eq(true, ZYwdwgd::getCreateId, loginUser.getUserId());
            }
            // 下场日期 完工日期
            if (bo.getParams()!=null && bo.getParams().size() > 0) {
                // 下场
                Object startTime = bo.getParams().get("startXcrq");
                Object endTime = bo.getParams().get("endXcrq");
                if (null != startTime && null != endTime) {
                    lqw.ge(ZYwdwgd::getXcrq, startTime);
                    lqw.le(ZYwdwgd::getXcrq, endTime);
                }
                // 完工
                Object startWgTime = bo.getParams().get("startWgrq");
                Object endWgTime = bo.getParams().get("endWgrq");
                if (null != startWgTime && null != endWgTime) {
                    lqw.ge(ZYwdwgd::getWgrq, startWgTime);
                    lqw.le(ZYwdwgd::getWgrq, endWgTime);
                }
                // 开票日期
                Object startKprq = bo.getParams().get("startKprq");
                Object endKprq = bo.getParams().get("endKprq");
                if (null != startKprq && null != endKprq) {
                    lqw.ge(ZYwdwgd::getKprq, startKprq);
                    lqw.le(ZYwdwgd::getKprq, endKprq);
                }
                // 回款日期
                Object startHkrq = bo.getParams().get("startHkrq");
                Object endHkrq = bo.getParams().get("endHkrq");
                if (null != startHkrq && null != endHkrq) {
                    lqw.ge(ZYwdwgd::getKprq, startHkrq);
                    lqw.le(ZYwdwgd::getKprq, endHkrq);
                }
            }
            // 完工单完善状态
            if(StringUtils.isNotEmpty(bo.getWgdWszt())) {
                String[] split = bo.getWgdWszt().split(",");
                boolean ws = Arrays.asList(split).contains("ws");
                boolean dlr = Arrays.asList(split).contains("dlr");
                boolean dws = Arrays.asList(split).contains("dws");
                if (ws && dlr && dws) {
                    lqw.and(w -> w.and(a -> a.isNotNull(ZYwdwgd::getWgdh).and(a1 -> a1.isNotNull(ZYwdwgd::getWgdfj)).and(w1 -> w1.ne(ZYwdwgd::getWgdfj, "")))
                        .or(a2 -> a2.isNull(ZYwdwgd::getWgdh).and(a3 -> a3.isNull(ZYwdwgd::getWgdfj)))
                        .or(a4 -> a4.isNotNull(ZYwdwgd::getWgdh).and(a5 -> a5.isNull(ZYwdwgd::getWgdfj)))
                    );
                }else if (ws && dlr) {
                    lqw.and(w -> w.and(a -> a.isNotNull(ZYwdwgd::getWgdh).and(a1 -> a1.isNotNull(ZYwdwgd::getWgdfj)).and(w1 -> w1.ne(ZYwdwgd::getWgdfj, "")))
                        .or(a2 -> a2.isNull(ZYwdwgd::getWgdh).and(a3 -> a3.isNull(ZYwdwgd::getWgdfj)))
                    );
                }else if (ws && dws) {
                    lqw.and(w -> w.and(a -> a.isNotNull(ZYwdwgd::getWgdh).and(a1 -> a1.isNotNull(ZYwdwgd::getWgdfj)).and(w1 -> w1.ne(ZYwdwgd::getWgdfj, "")))
                        .or(a2 -> a2.isNotNull(ZYwdwgd::getWgdh).and(a3 -> a3.isNull(ZYwdwgd::getWgdfj)))
                    );
                }else if (dlr && dws) {
                    lqw.and(w -> w.and(c -> c.isNull(ZYwdwgd::getWgdh).and(a -> a.isNull(ZYwdwgd::getWgdfj))).or(c -> c.isNotNull(ZYwdwgd::getWgdh).and(a -> a.isNull(ZYwdwgd::getWgdfj))));
                }else if (ws) {
                    lqw.and(w -> w.isNotNull(ZYwdwgd::getWgdfj).and(w1 -> w1.ne(ZYwdwgd::getWgdfj, "")).and(a -> a.isNotNull(ZYwdwgd::getWgdh)));
                }else if (dws) {
                    lqw.and(w -> w.isNotNull(ZYwdwgd::getWgdh).and(a -> a.isNull(ZYwdwgd::getWgdfj)));
                }else if (dlr) {
                    lqw.and(w -> w.isNull(ZYwdwgd::getWgdh).and(a -> a.isNull(ZYwdwgd::getWgdfj)));
                }
            }
            // 报价单完善状态
            if(StringUtils.isNotEmpty(bo.getBjdWszt())) {
                String[] split = bo.getBjdWszt().split(",");
                boolean ws = Arrays.asList(split).contains("ws");
                boolean dws = Arrays.asList(split).contains("dws");
                if (ws && dws) {
                    lqw.and(w -> w.isNotNull(ZYwdwgd::getBjdfj).and(w1 -> w1.ne(ZYwdwgd::getBjdfj, "")).or(a -> a.isNull(ZYwdwgd::getBjdfj)));
//                    lqw.and(w -> w.isNotNull(ZYwdwgd::getBjdfj)).or(w -> w.isNull(ZYwdwgd::getBjdfj));
                }else if (ws) {
                    lqw.and(w -> w.isNotNull(ZYwdwgd::getBjdfj)).and(w1 -> w1.ne(ZYwdwgd::getBjdfj, ""));
                }else if (dws) {
                    lqw.and(w -> w.isNull(ZYwdwgd::getBjdfj)).or(w1 -> w1.eq(ZYwdwgd::getBjdfj, ""));
                }
            }
            // 用户是否确认
            if (StringUtils.isNotEmpty(bo.getYhsfqr())) {
                List<String> strings = Arrays.asList(bo.getYhsfqr().split(","));
                lqw.in(ZYwdwgd::getYhsfqr, strings);
            }
            // 是否回款
            if (StringUtils.isNotEmpty(bo.getSfhk())) {
                List<String> strings = Arrays.asList(bo.getSfhk().split(","));
                lqw.in(ZYwdwgd::getSfhk, strings);
            }
            // 今日昨天日期
            if (bo.getStartCreateTime() != null && bo.getEndCreateTime() != null) {
                lqw.ge(ZYwdwgd::getCreateTime, bo.getStartCreateTime())
                    .le(ZYwdwgd::getCreateTime, bo.getEndCreateTime());
            }
            // 下场状态
            if (StringUtils.isNotEmpty(bo.getXczt())) {  // 是否已下场
                List<String> strings = Arrays.asList(bo.getXczt().split(","));
                lqw.in(ZYwdwgd::getXczt, strings);
            }
            // 是否开票
            if (StringUtils.isNotEmpty(bo.getSfkp())) {  // 是否开票
                List<String> strings = Arrays.asList(bo.getSfkp().split(","));
                lqw.in(ZYwdwgd::getSfkp, strings);
            }
            // 已邮寄客户
            if (StringUtils.isNotEmpty(bo.getYyjkh())) {  // 是否开票
                List<String> strings = Arrays.asList(bo.getYyjkh().split(","));
                lqw.in(ZYwdwgd::getYyjkh, strings);
            }
            // 所属公司
            if (StringUtils.isNotEmpty(bo.getSsgs())) {
                List<String> strings = Arrays.asList(bo.getSsgs().split(","));
                lqw.in(ZYwdwgd::getSsgs, strings);
            }
            // 特殊处理
            if (StringUtils.isNotEmpty(bo.getTscl())) {
                List<String> strings = Arrays.asList(bo.getTscl().split(","));
                lqw.in(ZYwdwgd::getTscl, strings);
            }
            // 是否给客户电子档
            if (StringUtils.isNotEmpty(bo.getSfgkhdzd())) {
                List<String> strings = Arrays.asList(bo.getSfgkhdzd().split(","));
                lqw.in(ZYwdwgd::getSfgkhdzd, strings);
            }
            // 申请电子档
            if (StringUtils.isNotEmpty(bo.getSfsqdzd())) {
                List<String> strings = Arrays.asList(bo.getSfsqdzd().split(","));
                lqw.in(ZYwdwgd::getSfsqdzd, strings);
            }
            // 纸质打印
            if (StringUtils.isNotEmpty(bo.getZzdy())) {
                List<String> strings = Arrays.asList(bo.getZzdy().split(","));
                lqw.in(ZYwdwgd::getZzdy, strings);
            }
            // 已邮寄客户
            if (StringUtils.isNotEmpty(bo.getYyjkh())) {
                List<String> strings = Arrays.asList(bo.getYyjkh().split(","));
                lqw.in(ZYwdwgd::getYyjkh, strings);
            }
            // 下场通知用户
            if (StringUtils.isNotEmpty(bo.getXctzyh())) {
                List<String> strings = Arrays.asList(bo.getXctzyh().split(","));
                lqw.in(ZYwdwgd::getXctzyh, strings);
            }
            // 待申请电子证书
            if (StringUtils.isNotEmpty(bo.getSfsqdzd())) {
                List<String> strings = Arrays.asList(bo.getSfsqdzd().split(","));
                lqw.in(ZYwdwgd::getSfsqdzd, strings);
            }

            // 从前端获取排序
            String orderByCode = bo.getOrderByCode();
            if (StringUtils.isNotEmpty(orderByCode)) {
                lqw = getOrder(lqw, orderByCode);
            }else {
                // 排序
                lqw.orderByDesc(ZYwdwgd::getXcrq);
                lqw.orderByDesc(ZYwdwgd::getCreateTime);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }

        return lqw;
    }

    private LambdaQueryWrapper<ZYwdwgd> getOrder(LambdaQueryWrapper<ZYwdwgd> lqw, String orderByCode) {
        String[] split = orderByCode.split(",");
        String file = split[0];
        String order = split[1];
        switch (file) {
            case "bjdh":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getBjdh) : lqw.orderByDesc(ZYwdwgd::getBjdh);
                break;
            case "wgdh":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getWgdh) : lqw.orderByDesc(ZYwdwgd::getWgdh);
                break;
            case "khname":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getKhname) : lqw.orderByDesc(ZYwdwgd::getKhname);
                break;
            case "jcfs":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getJcfs) : lqw.orderByDesc(ZYwdwgd::getJcfs);
                break;
            case "xczt":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getXczt) : lqw.orderByDesc(ZYwdwgd::getXczt);
                break;
            case "sfhk":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getSfhk) : lqw.orderByDesc(ZYwdwgd::getSfhk);
                break;
            case "hkje":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getHkje) : lqw.orderByDesc(ZYwdwgd::getHkje);
                break;
            case "hkrq":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getHkrq) : lqw.orderByDesc(ZYwdwgd::getHkrq);
                break;
            case "xcrq":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getXcrq) : lqw.orderByDesc(ZYwdwgd::getXcrq);
                break;
            case "kprq":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getKprq) : lqw.orderByDesc(ZYwdwgd::getKprq);
                break;
            case "bz":
                lqw = "asc".equals(order)?lqw.orderByAsc(ZYwdwgd::getBz) : lqw.orderByDesc(ZYwdwgd::getBz);
                break;
        }
        return lqw;
    }

    /**
     * 新增业务完工单
     */
    @Override
    public Boolean insertByBo(ZYwdwgdBo bo) {
        ZYwdwgd add = BeanUtil.toBean(bo, ZYwdwgd.class);
        // 如果新增的时候开票日期不为空则，将当前的日期进行添加
        if (bo.getKprq() != null) {
            add.setXzkpsj(DateUtils.getNowDate());
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        add.setCreateId(loginUser.getUserId()+"");
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        handleLog(0, add, null);
        return flag;
    }

    /**
     * 修改业务完工单
     */
    @Override
    public Boolean updateByBo(ZYwdwgdBo bo) {
        ZYwdwgd update = BeanUtil.toBean(bo, ZYwdwgd.class);
        // 开票日期不为空，并且查询当前数据是否有开票日期的时间
        ZYwdwgdVo obj = baseMapper.selectVoById(bo.getId());
        if (bo.getKprq() != null) {
            // 通过id查询一下详细信息
            if (obj.getXzkpsj() == null) {
                update.setXzkpsj(DateUtils.getNowDate());
            }
        }
        validEntityBeforeSave(update);
        // 修改之前先查询一下当前的数据
        ZYwdwgd updateBefore = BeanUtil.toBean(obj, ZYwdwgd.class);
        int i = baseMapper.updateById(update);
        if(StringUtils.isNotEmpty(bo.getIsLog()) && bo.getIsLog().equals("true")) {
            // 记录日志
            ZXcapLog zXcapLog = new ZXcapLog();
            zXcapLog.setXcid(update.getId());
            zXcapLog.setXcfzrid(update.getXcfzr());
            zXcapLog.setXcfzrname(update.getXcfzrname());
            zXcapLog.setXclx(update.getXclx());
            zXcapLog.setXcbz(update.getXcbz());
            zXcapLog.setXcsj(update.getXcrq());
            zXcapLog.setXcrid(update.getXcry());
            zXcapLog.setXcrname(update.getXcryname());
            zXcapLog.setCreatetime(new Date());
            zcapLogMapper.insert(zXcapLog);
            handleLog(2, updateBefore, update);
        }else {
            handleLog(1, updateBefore, update);
        }
        return i > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZYwdwgd entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除业务完工单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
    @Override
    public void resetDatabase() {
        baseMapper.deleteYwdWgdAll();
        ZYwdBo zYwdBo = new ZYwdBo();
//        PageQuery pageQuery = new PageQuery();
//        pageQuery.setPageNum(1);
//        pageQuery.setPageSize(300);
//        TableDataInfo<ZYwdVo> ywdData = zywgdService.queryPageList(zYwdBo, pageQuery, "ywd");
        List<ZYwdVo> rows = zywgdService.queryList(zYwdBo, "ywd");
        List<String> wgdIds = new ArrayList<>();
        List<ZYwdwgd> dataList = new ArrayList<>();
        for (ZYwdVo ywd : rows) {
            // 通过业务单编号查询完工单
            ZWgdBo zWgdBo = new ZWgdBo();
            zWgdBo.setZbbh(ywd.getZbbh());
            List<ZWgdVo> wgdList = wgdService.queryList(zWgdBo);
            if (wgdList.size() >= 1) {
                for (int i=0; i<wgdList.size(); i++) {
                    ZWgdVo wgd = wgdList.get(i);
                    ZYwdwgd zYwdwgd = new ZYwdwgd();
                    if (i > 0) {
                        zYwdwgd.setBjdh(ywd.getZbbh() + i);
                        zYwdwgd.setId(wgd.getId());
                    }else {
                        zYwdwgd.setId(ywd.getId());
                        zYwdwgd.setBjdh(ywd.getZbbh());
                    }
                    zYwdwgd.setKhid(ywd.getKhid());
                    zYwdwgd.setKhname(ywd.getKh());
                    zYwdwgd.setKhdz(ywd.getDz());
                    zYwdwgd.setBjdfj(ywd.getFj());
                    zYwdwgd.setBjdfjpdf(ywd.getFjpdf());
                    zYwdwgd.setHtje(ywd.getHtje());
                    zYwdwgd.setKhsh(wgd.getSh());
                    zYwdwgd.setWgdh(wgd.getWgbh());
                    zYwdwgd.setWgrq(wgd.getWgrq());
                    zYwdwgd.setBjrq(ywd.getCreateTime());
                    zYwdwgd.setWgdfj(wgd.getFj());
                    zYwdwgd.setWgdfjpdf(wgd.getFjpdf());
                    zYwdwgd.setXcfzr(ywd.getXcfzrid());
                    zYwdwgd.setXcfzrname(ywd.getXcfzrname());
                    zYwdwgd.setXcry(ywd.getXcryid());
                    zYwdwgd.setXcryname(ywd.getXcryname());
                    zYwdwgd.setXclx(ywd.getXclx());
                    zYwdwgd.setSfsqdzd("0");
                    zYwdwgd.setSfgkhdzd("0");
                    zYwdwgd.setZzdy("0");
                    zYwdwgd.setYyjkh("0");
                    zYwdwgd.setYhsfqr("0");
                    zYwdwgd.setXctzyh("0");
                    if ("Y".equals(wgd.getSfykfp())) {
                        zYwdwgd.setSfkp("1");
                    }else if ("N".equals(wgd.getSfykfp())){
                        zYwdwgd.setSfkp("0");
                    }
                    zYwdwgd.setKpje(wgd.getKpje());
                    zYwdwgd.setFph(wgd.getFpph());
                    zYwdwgd.setKprq(wgd.getKprq());
                    zYwdwgd.setTscl("0");
                    zYwdwgd.setSfhk(ywd.getSfhk());
                    zYwdwgd.setHkje(ywd.getHkje());
                    Date hksj = ywd.getHksj();
//                    if (hksj != null) {
//                        String format1 = format.format(hksj);
//                        hksj = new Date(format1);
//                    }
                    zYwdwgd.setHkrq(hksj);
                    zYwdwgd.setDzzh(wgd.getDzzh());
                    zYwdwgd.setSsgs("tjfgs");
                    String bz = "";
                    if (StringUtils.isNotEmpty(ywd.getBz())) {
                        bz += "报价单备注：" + ywd.getBz() + "。  ";
                    }
                    if (StringUtils.isNotEmpty(wgd.getBz())) {
                        bz += "完工单备注：" + wgd.getBz() + "。  ";
                    }
                    zYwdwgd.setBz(bz);
                    String jcfs = ywd.getJcfs();
                    zYwdwgd.setJcfs(jcfs);
                    if ("1".equals(jcfs)) {  // 下场
                        zYwdwgd.setXcrq(ywd.getXcsj());
                        zYwdwgd.setXczt(ywd.getSfyxc());
                    } else if ("2".equals(jcfs)) {  // 送检
                        Date sjsj = ywd.getSjsj();
                        if (sjsj == null) {
                            sjsj = ywd.getShsj();
                        }
                        zYwdwgd.setXcrq(sjsj);
                        String sjzt = ywd.getSjzt();
                        if ("0".equals(sjzt)) {
                            zYwdwgd.setXczt("4");
                        }else if ("1".equals(sjzt)) {
                            zYwdwgd.setXczt("5");
                        }else if ("2".equals(sjzt)) {
                            zYwdwgd.setXczt("6");
                        }else {
                            zYwdwgd.setXczt("4");
                        }
                    }
                    zYwdwgd.setDelFlag(ywd.getDelFlag());
                    zYwdwgd.setCreateId(ywd.getCreateId());
                    zYwdwgd.setCreateTime(ywd.getCreateTime());
                    dataList.add(zYwdwgd);
                    // 将完工单的id存入list中
                    wgdIds.add(wgd.getId());
                }
            }else if(wgdList.size() == 0) {
                ZYwdwgd zYwdwgd = new ZYwdwgd();
                zYwdwgd.setId(ywd.getId());
                zYwdwgd.setBjdh(ywd.getZbbh());
                zYwdwgd.setKhid(ywd.getKhid());
                zYwdwgd.setKhname(ywd.getKh());
                zYwdwgd.setKhdz(ywd.getDz());
                zYwdwgd.setBjdfj(ywd.getFj());
                zYwdwgd.setBjdfjpdf(ywd.getFjpdf());
                zYwdwgd.setHtje(ywd.getHtje());
                zYwdwgd.setBjrq(ywd.getCreateTime());
                zYwdwgd.setXcfzr(ywd.getXcfzrid());
                zYwdwgd.setXcfzrname(ywd.getXcfzrname());
                zYwdwgd.setXcry(ywd.getXcryid());
                zYwdwgd.setXcryname(ywd.getXcryname());
                zYwdwgd.setXclx(ywd.getXclx());
                zYwdwgd.setSfsqdzd("0");
                zYwdwgd.setSfgkhdzd("0");
                zYwdwgd.setZzdy("0");
                zYwdwgd.setYyjkh("0");
                zYwdwgd.setYhsfqr("0");
                zYwdwgd.setXctzyh("0");
                zYwdwgd.setTscl("0");
                zYwdwgd.setSsgs("tjfgs");
                String bz = "";
                if (StringUtils.isNotEmpty(ywd.getBz())) {
                    bz += "报价单备注：" + ywd.getBz() + "。  ";
                }
                zYwdwgd.setBz(bz);
                String jcfs = ywd.getJcfs();
                zYwdwgd.setJcfs(jcfs);
                if ("1".equals(jcfs)) {  // 下场
                    zYwdwgd.setXcrq(ywd.getXcsj());
                    zYwdwgd.setXczt(ywd.getSfyxc());
                } else if ("2".equals(jcfs)) {  // 送检
                    Date sjsj = ywd.getSjsj();
                    if (sjsj == null) {
                        sjsj = ywd.getShsj();
                    }
                    zYwdwgd.setXcrq(sjsj);
                    String sjzt = ywd.getSjzt();
                    if ("0".equals(sjzt)) {
                        zYwdwgd.setXczt("4");
                    }else if ("1".equals(sjzt)) {
                        zYwdwgd.setXczt("5");
                    }else if ("2".equals(sjzt)) {
                        zYwdwgd.setXczt("6");
                    }else {
                        zYwdwgd.setXczt("4");
                    }
                }
                zYwdwgd.setDelFlag(ywd.getDelFlag());
                zYwdwgd.setCreateId(ywd.getCreateId());
                zYwdwgd.setCreateTime(ywd.getCreateTime());
                dataList.add(zYwdwgd);
            }else {
                for (ZWgdVo wgd : wgdList) {
                    ZYwdwgd zYwdwgd = new ZYwdwgd();
                    zYwdwgd.setId(ywd.getId());
                    zYwdwgd.setBjdh(ywd.getZbbh());
                    zYwdwgd.setKhid(ywd.getKhid());
                    zYwdwgd.setKhname(ywd.getKh());
                    zYwdwgd.setKhdz(ywd.getDz());
                    zYwdwgd.setBjdfj(ywd.getFj());
                    zYwdwgd.setBjdfjpdf(ywd.getFjpdf());
                    zYwdwgd.setHtje(ywd.getHtje());
                    zYwdwgd.setKhsh(wgd.getSh());
                    zYwdwgd.setWgdh(wgd.getWgbh());
                    zYwdwgd.setWgrq(wgd.getWgrq());
                    zYwdwgd.setBjrq(ywd.getCreateTime());
                    zYwdwgd.setWgdfj(wgd.getFj());
                    zYwdwgd.setWgdfjpdf(wgd.getFjpdf());
                    zYwdwgd.setXcfzr(ywd.getXcfzrid());
                    zYwdwgd.setXcfzrname(ywd.getXcfzrname());
                    zYwdwgd.setXcry(ywd.getXcryid());
                    zYwdwgd.setXcryname(ywd.getXcryname());
                    zYwdwgd.setXclx(ywd.getXclx());
                    zYwdwgd.setSfsqdzd("0");
                    zYwdwgd.setSfgkhdzd("0");
                    zYwdwgd.setZzdy("0");
                    zYwdwgd.setYyjkh("0");
                    zYwdwgd.setYhsfqr("0");
                    zYwdwgd.setXctzyh("0");
                    if ("Y".equals(wgd.getSfykfp())) {
                        zYwdwgd.setSfkp("1");
                    }else if ("N".equals(wgd.getSfykfp())){
                        zYwdwgd.setSfkp("0");
                    }
                    zYwdwgd.setKpje(wgd.getKpje());
                    zYwdwgd.setFph(wgd.getFpph());
                    zYwdwgd.setKprq(wgd.getKprq());
                    zYwdwgd.setTscl("0");
                    zYwdwgd.setSfhk(ywd.getSfhk());
                    zYwdwgd.setHkje(ywd.getHkje());
                    Date hksj = ywd.getHksj();
//                    if (hksj != null) {
//                        String format1 = format.format(hksj);
//                        hksj = new Date(format1);
//                    }
                    zYwdwgd.setHkrq(hksj);
                    zYwdwgd.setDzzh(wgd.getDzzh());
                    zYwdwgd.setSsgs("tjfgs");
                    String bz = "";
                    if (StringUtils.isNotEmpty(ywd.getBz())) {
                        bz += "报价单备注：" + ywd.getBz() + "。  ";
                    }
                    if (StringUtils.isNotEmpty(wgd.getBz())) {
                        bz += "完工单备注：" + wgd.getBz() + "。  ";
                    }
                    zYwdwgd.setBz(bz);
                    String jcfs = ywd.getJcfs();
                    zYwdwgd.setJcfs(jcfs);
                    if ("1".equals(jcfs)) {  // 下场
                        zYwdwgd.setXcrq(ywd.getXcsj());
                        zYwdwgd.setXczt(ywd.getSfyxc());
                    } else if ("2".equals(jcfs)) {  // 送检
                        Date sjsj = ywd.getSjsj();
                        if (sjsj == null) {
                            sjsj = ywd.getShsj();
                        }
                        zYwdwgd.setXcrq(sjsj);
                        String sjzt = ywd.getSjzt();
                        if ("0".equals(sjzt)) {
                            zYwdwgd.setXczt("4");
                        }else if ("1".equals(sjzt)) {
                            zYwdwgd.setXczt("5");
                        }else if ("2".equals(sjzt)) {
                            zYwdwgd.setXczt("6");
                        }else {
                            zYwdwgd.setXczt("4");
                        }
                    }
                    zYwdwgd.setDelFlag(ywd.getDelFlag());
                    zYwdwgd.setCreateId(ywd.getCreateId());
                    zYwdwgd.setCreateTime(ywd.getCreateTime());
                    dataList.add(zYwdwgd);
                    // 将完工单的id存入list中
                    wgdIds.add(wgd.getId());
                }
            }

        }
        // 将数据进行批量添加以及批量修改
        boolean b = baseMapper.insertBatch(dataList);
        // 将完工单数据进行批量修改
        int row = wgdService.batchUpdateById(wgdIds);

        // 查询只有完工单的数据
        List<ZWgdVo> wclWgdList = wgdService.selectWcl();
        List<ZYwdwgd> updateList = new ArrayList<>();
        for (ZWgdVo wgd : wclWgdList) {
            ZYwdwgd zYwdwgd = new ZYwdwgd();
            zYwdwgd.setId(wgd.getId());
            zYwdwgd.setBjdh(wgd.getZbbh());
            zYwdwgd.setKhname(wgd.getKhname());
            zYwdwgd.setKhdz(wgd.getDz());
            zYwdwgd.setKhsh(wgd.getSh());
            zYwdwgd.setWgdh(wgd.getWgbh());
            zYwdwgd.setWgrq(wgd.getWgrq());
            zYwdwgd.setWgdfj(wgd.getFj());
            zYwdwgd.setWgdfjpdf(wgd.getFjpdf());
            zYwdwgd.setSfsqdzd("0");
            zYwdwgd.setSfgkhdzd("0");
            zYwdwgd.setZzdy("0");
            zYwdwgd.setYyjkh("0");
            zYwdwgd.setYhsfqr("0");
            zYwdwgd.setXctzyh("0");
            if ("Y".equals(wgd.getSfykfp())) {
                zYwdwgd.setSfkp("1");
            }else if ("N".equals(wgd.getSfykfp())){
                zYwdwgd.setSfkp("0");
            }
            zYwdwgd.setKpje(wgd.getKpje());
            zYwdwgd.setFph(wgd.getFpph());
            zYwdwgd.setKprq(wgd.getKprq());
            zYwdwgd.setTscl("0");
            zYwdwgd.setSfhk(wgd.getSfhk());
            zYwdwgd.setHkje(wgd.getHkje());
            Date hksj = wgd.getHksj();
//            if (hksj != null) {
//                String format1 = format.format(hksj);
//                hksj = new Date(format1);
//            }
            zYwdwgd.setHkrq(hksj);
            zYwdwgd.setDzzh(wgd.getDzzh());
            zYwdwgd.setSsgs("tjfgs");
            String bz = "";
            if (StringUtils.isNotEmpty(wgd.getBz())) {
                bz += "完工单备注：" + wgd.getBz() + "。  ";
            }
            zYwdwgd.setBz(bz);
            zYwdwgd.setDelFlag(wgd.getDelFlag());
            zYwdwgd.setXczt("1");
            zYwdwgd.setCreateTime(wgd.getCreateTime());
            updateList.add(zYwdwgd);
        }
        // 将只有完工单的数据进行添加
        baseMapper.insertBatch(updateList);
    }

    // 通过完工编号批量修改
    @Override
    public int batchUpdateByWgbh(List<ZYwdwgdBo> zywdwgdList) {
        int row = 0;
        for (ZYwdwgdBo zYwdwgdBo : zywdwgdList) {
            row += baseMapper.batchUpdateByWgbh(zYwdwgdBo);
        }
        return row;
    }

    // 批量修改状态
    @Override
    public Boolean batchUpdateZt(ZYwdwgdBo bo) {
        String[] split = bo.getId().split(",");
        int row = baseMapper.batchUpdateZt(bo, split);
        return row > 0;
    }

    @Override
    public byte[] genDzd(String ids, String type) {
        // 通过id查询出数据
        List<ZYwdwgdVo> zYwdwgdVos = baseMapper.queryListByIds(ids.split(","));
        // 判断当前申请的是电子档还是纸质证书
        if("dzd".equals(type)) {
            return handleDzd(zYwdwgdVos);
        }else if("zyzz".equals(type)) {
            return handleDzdZz(zYwdwgdVos, type);
        }else {
            return handleDzdZz(zYwdwgdVos, type);
        }
    }

    @Override
    public byte[] genDzdNew(String ids, String type) {
        // 通过id查询出数据
        List<ZYwdwgdVo> zYwdwgdVos = baseMapper.queryListByIds(ids.split(","));
        // 判断当前申请的是电子档还是纸质证书
        return handleDzdNew(zYwdwgdVos, type);
    }

    private byte[] handleDzdNew(List<ZYwdwgdVo> zYwdwgdVos, String type) {
        // 创建要填充的数据
        JSONArray array = new JSONArray();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < zYwdwgdVos.size(); i++) {
            ZYwdwgdVo zYwdwgdVo = zYwdwgdVos.get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("khname", zYwdwgdVo.getKhname()+zYwdwgdVo.getWgdh());
            jsonObject.put("zjfs", zYwdwgdVo.getZjfs());
            jsonObject.put("hkje", (int) Math.floor(zYwdwgdVo.getHkje()));
            jsonObject.put("hkrq", format.format(addThreeMonths(zYwdwgdVo.getXcrq())));
            if ("dzd".equals(type)) {
                jsonObject.put("clfs", "电子档");
            }else if ("zyzz".equals(type)) {
                jsonObject.put("clfs", "打印");
            }else {
                jsonObject.put("clfs", "电子+打印");
            }
            jsonObject.put("sjxcrq", format.format(zYwdwgdVo.getXcrq()));
            array.add(jsonObject);
        }
        try {
            String excelUrl = getTemplatePath("template/dzdmbNew.xlsx");
            FileInputStream fis = new FileInputStream(excelUrl);
            Workbook fileWorkbook = new XSSFWorkbook(fis);
            Sheet sheet = fileWorkbook.getSheetAt(0);
            // 遍历文档数据
            int lastRowNum = sheet.getLastRowNum();
            for (int i = 0; i < array.size(); i++) {
                JSONObject json = array.getJSONObject(i);
                int rowIndex = lastRowNum + i + 1;
                Row row = sheet.createRow(rowIndex);
                Cell one = row.createCell(0);
                Cell two = row.createCell(1);
                Cell three = row.createCell(2);
                Cell four = row.createCell(3);
                Cell five = row.createCell(4);
                Cell six = row.createCell(5);
                one.setCellValue(json.getStr("khname")); two.setCellValue(json.getInt("zjfs"));
                three.setCellValue(json.getStr("hkje")); four.setCellValue(json.getStr("hkrq"));
                five.setCellValue(json.getStr("clfs")); six.setCellValue(json.getStr("sjxcrq"));
                setStyle(fileWorkbook, one); setStyle(fileWorkbook, two); setStyle(fileWorkbook, three);
                setStyle(fileWorkbook, four); setStyle(fileWorkbook, five); setStyle(fileWorkbook, six);
            }
            // 获取当前下载excel的路径
            LocalDate currentDate = LocalDate.now();
            // 分别获取年、月、日
            int year = currentDate.getYear();
            int monthValue = currentDate.getMonthValue();
            int dayOfMonth = currentDate.getDayOfMonth();
            // 生成Excel路径
            String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/temp_dzd/";
            // 判断当前文件路径的文件夹是否存在，不存在则创建
            if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
                // 路径不存在，尝试创建
                try {
                    Files.createDirectories(Paths.get(uploadPath + suffixPath));
                } catch (Exception e) {
                    System.err.println("创建目录时出错: " + e.getMessage());
                }
            }
            String rq = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String fileName = "";
            if ("zyzz".equals(type)) {
                fileName = "纸质" + "_"+ rq + ".xlsx";
            }else {
                fileName = "电子和纸质" + "_"+ rq + ".xlsx";
            }
            String path = uploadPath + suffixPath + fileName;
            // 输出填充数据后的Word文档
            FileOutputStream out = new FileOutputStream(path);
            fileWorkbook.write(out);
            out.close();
            fileWorkbook.close();
            FileInputStream inputStream = new FileInputStream(path);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            inputStream.close();
            return bytes;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    // 设置边框样式
    public void setStyle(Workbook workbook, Cell cell) {
        // 创建样式
        CellStyle style = workbook.createCellStyle();
        // 设置边框样式
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        // 设置边框颜色
        style.setTopBorderColor(IndexedColors.BLACK.getIndex());
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
        style.setRightBorderColor(IndexedColors.BLACK.getIndex());
        // 设置单元格的水平对齐方式为居中
        style.setAlignment(HorizontalAlignment.CENTER);
        // 设置单元格的垂直对齐方式为居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        // 设置字体为宋体
        Font font = workbook.createFont();
        font.setFontName("SimSun");  // 设置字体为宋体
        style.setFont(font);
        style.setWrapText(true); // 启用自动换行
        // 样式应用单元格
        cell.setCellStyle(style);
    }

    // 申请纸质
    private byte[] handleDzdZz(List<ZYwdwgdVo> zYwdwgdVos, String type){
        // 创建要填充的数据
        JSONArray array = new JSONArray();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < zYwdwgdVos.size(); i++) {
            ZYwdwgdVo zYwdwgdVo = zYwdwgdVos.get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("xh", i+1);
            jsonObject.put("khname", zYwdwgdVo.getKhname()+zYwdwgdVo.getWgdh());
            jsonObject.put("zjfs", zYwdwgdVo.getZjfs());
            jsonObject.put("hkje", (int) Math.floor(zYwdwgdVo.getHkje()));
            jsonObject.put("hkrq", format.format(addThreeMonths(zYwdwgdVo.getXcrq())));
            if ("zyzz".equals(type)) {
                jsonObject.put("clfs", "纸质");
            }else {
                jsonObject.put("clfs", "电子和纸质");
            }
            jsonObject.put("sjxcrq", format.format(zYwdwgdVo.getXcrq()));
            array.add(jsonObject);
        }
        try {
            String excelUrl = getTemplatePath("template/sqzzwj.docx");
            FileInputStream fis = new FileInputStream(excelUrl);
            XWPFDocument document = new XWPFDocument(fis);

            // 找到需要填充数据的表格位置
            for (XWPFTable documentTable : document.getTables()) {
                if (documentTable.getText().contains("序号")
                    && documentTable.getText().contains("证书")
                    && documentTable.getText().contains("公司名称")) {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        XWPFTableRow row = documentTable.createRow();
                        XWPFTableCell one = row.getCell(0);
                        XWPFTableCell two = row.getCell(1);
                        XWPFTableCell three = row.getCell(2);
                        XWPFTableCell four = row.getCell(3);
                        XWPFTableCell five = row.getCell(4);
                        XWPFTableCell six = row.getCell(5);
                        XWPFTableCell seven = row.getCell(6);
                        one.setText(obj.getStr("xh"));
                        two.setText(obj.getStr("khname"));
                        three.setText(obj.getStr("zjfs"));
                        four.setText(obj.getStr("hkje"));
                        five.setText(obj.getStr("hkrq"));
                        six.setText(obj.getStr("clfs"));
                        seven.setText(obj.getStr("sjxcrq"));
                        setCellBorders(one); setTextAlignment(one, ParagraphAlignment.CENTER); // 设置样式
                        setCellBorders(two); setTextAlignment(two, ParagraphAlignment.CENTER);
                        setCellBorders(three); setTextAlignment(three, ParagraphAlignment.CENTER);
                        setCellBorders(four); setTextAlignment(four, ParagraphAlignment.CENTER);
                        setCellBorders(five); setTextAlignment(five, ParagraphAlignment.CENTER);
                        setCellBorders(six); setTextAlignment(six, ParagraphAlignment.CENTER);
                        setCellBorders(seven); setTextAlignment(seven, ParagraphAlignment.CENTER);

                    }
                }
            }

            // 获取当前下载excel的路径
            LocalDate currentDate = LocalDate.now();
            // 分别获取年、月、日
            int year = currentDate.getYear();
            int monthValue = currentDate.getMonthValue();
            int dayOfMonth = currentDate.getDayOfMonth();
            // 生成Excel路径
            String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/temp_dzd/";
            // 判断当前文件路径的文件夹是否存在，不存在则创建
            if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
                // 路径不存在，尝试创建
                try {
                    Files.createDirectories(Paths.get(uploadPath + suffixPath));
                } catch (Exception e) {
                    System.err.println("创建目录时出错: " + e.getMessage());
                }
            }
            String rq = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String fileName = "";
            if ("zyzz".equals(type)) {
                fileName = "纸质" + "_"+ rq + ".docx";
            }else {
                fileName = "电子和纸质" + "_"+ rq + ".docx";
            }
            String path = uploadPath + suffixPath + fileName;
            // 输出填充数据后的Word文档
            FileOutputStream out = new FileOutputStream(path);
            document.write(out);
            out.close();
            document.close();
            FileInputStream inputStream = new FileInputStream(path);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            inputStream.close();
            return bytes;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    // 设置边框
    private void setCellBorders(XWPFTableCell cell) {
        CTTc tc = cell.getCTTc();
        CTTcPr tcPr = tc.isSetTcPr() ? tc.getTcPr() : tc.addNewTcPr();
        // 设置边框
        CTBorder border = CTBorder.Factory.newInstance();
        border.setSz(BigInteger.valueOf(1)); // 线宽
        border.setVal(STBorder.SINGLE); // 线型
        border.setColor("auto"); // 颜色
        // 设置单元格的边框
        CTTcBorders borders = tcPr.isSetTcBorders() ? tcPr.getTcBorders() : tcPr.addNewTcBorders();
        borders.setBottom(border);
        borders.setTop(border);
        borders.setLeft(border);
        borders.setRight(border);

    }

    // 设置文本居中
    private void setTextAlignment(XWPFTableCell cell, ParagraphAlignment alignment) {
        List<XWPFParagraph> paragraphs = cell.getParagraphs();
        for (XWPFParagraph paragraph : paragraphs) {
            paragraph.setAlignment(alignment);
        }
    }

    // 申请电子档
    private byte[] handleDzd(List<ZYwdwgdVo> zYwdwgdVos) {
        // 1.先获取当前要生成的数据
        JSONArray array = new JSONArray();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < zYwdwgdVos.size(); i++) {
            ZYwdwgdVo zYwdwgdVo = zYwdwgdVos.get(i);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("xh", i+1);
            jsonObject.put("khname", zYwdwgdVo.getKhname()+zYwdwgdVo.getWgdh());
            jsonObject.put("zjfs", zYwdwgdVo.getZjfs());
            jsonObject.put("hkje", zYwdwgdVo.getHkje());
            jsonObject.put("hkrq", addThreeMonths(zYwdwgdVo.getXcrq()));
            jsonObject.put("clfs", "电子档");
            jsonObject.put("sjxcrq", format.format(zYwdwgdVo.getXcrq()));
            array.add(jsonObject);
        }
        // 2.获取当前的模板
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try  {
            // 获取模板的路径
            String excelUrl = getTemplatePath("template/dzdmb.xls");
            fileInputStream = new FileInputStream(excelUrl);
            Workbook fileWorkbook = new HSSFWorkbook(fileInputStream);
            Sheet sheetData = fileWorkbook.getSheetAt(0);
            // 将第二行
            sheetData.shiftRows(1, sheetData.getLastRowNum(), array.size());
            // 创建样式
            CellStyle style = fileWorkbook.createCellStyle();
            // 设置单元格文字居中
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            // 填充数据
            for (int i = 0; i < array.size(); i++) {
                // 获取当前的数据
                JSONObject rowData = array.getJSONObject(i);
                Integer currentRow = 1 + i;
                // 当前是填充数据
                Row newRow = sheetData.createRow(currentRow);  // 当前行
                Cell xh = newRow.createCell(0);   // 序号
                Cell gsmc = newRow.createCell(1);    // 公司名称
                Cell zs = newRow.createCell(2);    // 证书
                Cell wgje = newRow.createCell(3);  // 完工单金额
                Cell hkrq = newRow.createCell(4);   // 预计回款日期
                Cell clfs = newRow.createCell(5);   // 处理方式
                Cell bz = newRow.createCell(6);   // 备注

                // 填充数据
                xh.setCellValue(rowData.getInt("xh"));
                gsmc.setCellValue(rowData.getStr("khname"));
                zs.setCellValue(rowData.getInt("zjfs"));
                wgje.setCellValue(rowData.getDouble("hkje"));
                hkrq.setCellValue(rowData.getDate("hkrq"));
                clfs.setCellValue(rowData.getStr("clfs"));
                bz.setCellValue(rowData.getStr("sjxcrq"));

                CellStyle dateCellStyle = fileWorkbook.createCellStyle();
                CreationHelper createHelper = fileWorkbook.getCreationHelper();
                dateCellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-mm-dd"));
                dateCellStyle.setAlignment(HorizontalAlignment.CENTER);
                dateCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
                dateCellStyle.setBorderTop(BorderStyle.THIN);
                dateCellStyle.setBorderBottom(BorderStyle.THIN);
                dateCellStyle.setBorderLeft(BorderStyle.THIN);
                dateCellStyle.setBorderRight(BorderStyle.THIN);

                // 设置每一行样式
                xh.setCellStyle(style);
                gsmc.setCellStyle(style);
                zs.setCellStyle(style);
                wgje.setCellStyle(style);
                hkrq.setCellStyle(dateCellStyle);
                clfs.setCellStyle(style);
                bz.setCellStyle(style);
                newRow.setHeightInPoints(69);  // 设置行高
            }

            // ==================== 生成图片  ================
            // 获取行和列
            int rowIndex = sheetData.getLastRowNum();
            int columnIndex = 5; // 第2列
            for (int row = 0; row <= sheetData.getLastRowNum(); row++){
                Row rowData = sheetData.getRow(row);
                if (rowData != null) {
                    Cell cell = rowData.getCell(0);
                    if (cell != null && StringUtils.isNotEmpty(cell.toString()) && cell.toString().contains("备注说明")) {
                        rowIndex = rowData.getRowNum();
                        break;
                    }
                }
            }
            // 创建一个绘图对象
            Drawing<?> drawing = sheetData.createDrawingPatriarch();
            ClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, columnIndex, rowIndex, columnIndex + 3, rowIndex + 9);
            // 获取图片路径
            String imgUrl = getTemplatePath("template/zhr.png");
            // 添加图片
            byte[] imageBytes = getImageBytes(imgUrl);
            int pictureIndex = fileWorkbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
            Picture picture = drawing.createPicture(anchor, pictureIndex);
            picture.resize(0.4);
            // ==================== 生成图片  ================

            // 删除第五行（索引为 4）
//            Row rowToDelete = sheetData.getRow(4); // 索引从 0 开始
//            if (rowToDelete != null) {
//                sheetData.removeRow(rowToDelete);
//                sheetData.shiftRows(5, sheetData.getLastRowNum(), -1, true, true);
//            }

            // 获取当前下载excel的路径
            LocalDate currentDate = LocalDate.now();
            // 分别获取年、月、日
            int year = currentDate.getYear();
            int monthValue = currentDate.getMonthValue();
            int dayOfMonth = currentDate.getDayOfMonth();
            // 生成Excel路径
            String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/temp_dzd/";
            // 判断当前文件路径的文件夹是否存在，不存在则创建
            if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
                // 路径不存在，尝试创建
                try {
                    Files.createDirectories(Paths.get(uploadPath + suffixPath));
                } catch (Exception e) {
                    System.err.println("创建目录时出错: " + e.getMessage());
                }
            }
            String rq = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String fileName = "电子档" + "_"+ rq + ".xls";
            String path = uploadPath + suffixPath + fileName;
            fileOutputStream = new FileOutputStream(path);
            fileWorkbook.write(fileOutputStream);
            fileWorkbook.close();
            fileInputStream.close();
            FileInputStream inputStream = new FileInputStream(path);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            inputStream.close();
            return bytes;
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 为给定的日期增加三个月。
     *
     * @param date 给定的日期
     * @return 三个月后的日期
     */
    private Date addThreeMonths(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 3);
        return calendar.getTime();
    }

    @Override
    public List<ZFujianBo> szWgdToTjWgd(String tjFjId, String wgrq) {
        List<ZFujianVo> zFujianList = fujianService.queryListByIdOrdery(tjFjId);
        List<ZFujianBo> resultList = new ArrayList<>();
        for (ZFujianVo zFujianVo : zFujianList) {
            ZFujianBo result = handleClear(zFujianVo, wgrq);
            resultList.add(result);
        }
        return resultList;
    }

    public ZFujianBo handleClear(ZFujianVo zFujianVo, String wgrq) {
        String fjpath = uploadPath + zFujianVo.getFjpath();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fjpath);
            EasyExcelReadListener easyExcelReadListener = new EasyExcelReadListener(15);
            EasyExcel.read(fjpath, ReadExcelVo.class, easyExcelReadListener).sheet().doRead();
            // 获取当前的读取的数据
            List<ReadExcelVo> readExcelList = easyExcelReadListener.getReadExcelList();
            String htdh = easyExcelReadListener.getHtdh();  // 合同单号
            String khname = easyExcelReadListener.getKhname();  // 客户名称
            String dz = easyExcelReadListener.getDz();  // 地址

            // 获取模板，将数据填充到模板中
            String excelUrl = getTemplatePath("template/tjwgdmb.xlsx");
            fis = new FileInputStream(excelUrl);
            Workbook fileWorkbook = new XSSFWorkbook(fis);
            Sheet sheetOut = fileWorkbook.getSheetAt(0);
            int listRow = 0;
            JSONObject cellIndex = new JSONObject();
            // 遍历文档数据
            int lstRowOut = sheetOut.getLastRowNum();
            for (int i = 0; i < lstRowOut; i++) {
                Row row = sheetOut.getRow(i);
                int j = 0;
                for (Cell cell : row) {
                    if (cell != null && cell.toString().contains("${htdh}")) {
                        cell.setCellValue("合同单号：" + htdh);
                    } else if (cell != null && cell.toString().contains("${khname}")) {
                        cell.setCellValue("委托单位（甲方）：" + khname);
                    } else if (cell != null && cell.toString().contains("${dz}")) {
                        cell.setCellValue("地    址：" + dz);
                    } else if (cell != null && cell.toString().contains("${rq}")) {
                        cell.setCellValue("日期:" + wgrq);
                    } else if (cell != null && cell.toString().contains("${xh}")) {
                        listRow = row.getRowNum();
                        cellIndex.put("xh", j);
                    }else if (cell != null && cell.toString().contains("${yqmc}")) {
                        cellIndex.put("yqmc", j);
                    }else if (cell != null && cell.toString().contains("${xhgg}")) {
                        cellIndex.put("xhgg", j);
                    }else if (cell != null && cell.toString().contains("${zzc}")) {
                        cellIndex.put("zzc", j);
                    }else if (cell != null && cell.toString().contains("${ccbh}")) {
                        cellIndex.put("ccbh", j);
                    }else if (cell != null && cell.toString().contains("${glbh}")) {
                        cellIndex.put("glbh", j);
                    }else if (cell != null && cell.toString().contains("${sl}")) {
                        cellIndex.put("sl", j);
                    }else if (cell != null && cell.toString().contains("${dj}")) {
                        cellIndex.put("dj", j);
                    }else if (cell != null && cell.toString().contains("${xj}")) {
                        cellIndex.put("xj", j);
                    }else if (cell != null && cell.toString().contains("${fwfs}")) {
                        cellIndex.put("fwfs", j);
                    }else if (cell != null && cell.toString().contains("${bz}")) {
                        cellIndex.put("bz", j);
                    }
                    j++;
                }
            }
            // 在第7行（索引为6）前插入新行，将第7行及之后的行下移
            if(readExcelList.size()-1 > 0) {
                sheetOut.shiftRows(listRow+1, lstRowOut, readExcelList.size()-1);
            }
            String xjStr = "";
            // 遍历数据并创建行
            for (int i = 0; i < readExcelList.size(); i++) {
                // 获取第一个数据
                ReadExcelVo readExcelVo = readExcelList.get(i);
                int currenRow = listRow + i;
                Row newRow = sheetOut.createRow(currenRow);  // 在currentRow创建一行
                newRow.setHeightInPoints(25);  // 设置行高
                // 创建列
                for (int j = 0; j < 32; j++) {
                    Cell cell = newRow.createCell(j);
                    setStyle(fileWorkbook, cell);
                }
                // 创建单元格
                Cell xh = newRow.getCell(cellIndex.getInt("xh"));
                Cell yqmc = newRow.getCell(cellIndex.getInt("yqmc"));
                Cell xhgg = newRow.getCell(cellIndex.getInt("xhgg"));
                Cell zzc = newRow.getCell(cellIndex.getInt("zzc"));
                Cell ccbh = newRow.getCell(cellIndex.getInt("ccbh"));
                Cell glbh = newRow.getCell(cellIndex.getInt("glbh"));
                Cell sl = newRow.getCell(cellIndex.getInt("sl"));
                Cell dj = newRow.getCell(cellIndex.getInt("dj"));
                Cell xj = newRow.getCell(cellIndex.getInt("xj"));
                Cell fwfs = newRow.getCell(cellIndex.getInt("fwfs"));
                Cell bz = newRow.getCell(cellIndex.getInt("bz"));
                // 合并数据
                setMergeData(fileWorkbook, sheetOut, currenRow);
                // 设置数据
                xh.setCellValue(Integer.parseInt(readExcelVo.getXh()));
                yqmc.setCellValue(readExcelVo.getName());
                xhgg.setCellValue(readExcelVo.getXhgg());
                zzc.setCellValue(readExcelVo.getZzcs());
                ccbh.setCellValue(readExcelVo.getCcbh());
                glbh.setCellValue(readExcelVo.getGlbh());
                sl.setCellValue(Integer.parseInt(readExcelVo.getNumber()));
                dj.setCellValue(Double.parseDouble(readExcelVo.getDj()));
                fwfs.setCellValue(readExcelVo.getFwfs());
                bz.setCellValue(readExcelVo.getBz());
                // 设置小计
                String djFormat = new CellReference(currenRow, cellIndex.getInt("dj"), false, false).formatAsString();
                String slFormat = new CellReference(currenRow, cellIndex.getInt("sl"), false, false).formatAsString();
                xj.setCellFormula(djFormat + "*" + slFormat);
                // 记录小计的字段
                String xjFormat = new CellReference(currenRow, cellIndex.getInt("xj"), false, false).formatAsString();
                xjStr += xjFormat + ",";
            }
            xjStr = removeLastCharacter(xjStr);
            String[] split = xjStr.split(",");
            String xjData = "";
            if (split.length > 0) {
                String start = split[0];
                String end = split[split.length - 1];
                xjData = "SUM(" + start + ":" + end + ")";
            }
            // 设置校验总费用数据
            int currenRow = listRow + readExcelList.size();
            Row row = sheetOut.getRow(currenRow);
            if (StringUtils.isNotEmpty(xjData)) {
                Integer xj = cellIndex.getInt("xj");
                row.getCell(xj).setCellFormula(xjData);
            }

            // 设置合计总费用
            int zfyRowIndex = listRow + readExcelList.size() + 2;
            String one = new CellReference(zfyRowIndex - 1, cellIndex.getInt("xj"), false, false).formatAsString();
            String two = new CellReference(zfyRowIndex - 2, cellIndex.getInt("xj"), false, false).formatAsString();
            Row zfyRow = sheetOut.getRow(zfyRowIndex);
            String zfyData = "SUM(" + two + "," + one + ")";
            zfyRow.getCell(cellIndex.getInt("xj")).setCellFormula(zfyData);

            // 获取当前下载excel的路径
            LocalDate currentDate = LocalDate.now();
            // 分别获取年、月、日
            int year = currentDate.getYear();
            int monthValue = currentDate.getMonthValue();
            int dayOfMonth = currentDate.getDayOfMonth();
            // 生成Excel路径
            String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/temp_qxgd/";
            // 判断当前文件路径的文件夹是否存在，不存在则创建
            if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
                // 路径不存在，尝试创建
                try {
                    Files.createDirectories(Paths.get(uploadPath + suffixPath));
                } catch (Exception e) {
                    System.err.println("创建目录时出错: " + e.getMessage());
                }
            }
            String path = uploadPath + suffixPath + zFujianVo.getFjname();
            // 输出填充数据后的Word文档
            FileOutputStream out = new FileOutputStream(path);
            fileWorkbook.write(out);
            out.close();
            fileWorkbook.close();

            // 将当前的文件保存到附件表中
            ZFujianBo fujian = new ZFujianBo();
            fujian.setFjid(IdUtil.simpleUUID());  //设置附件id
            fujian.setFjname(zFujianVo.getFjname());   //设置附件名称
            fujian.setFjpath(suffixPath + zFujianVo.getFjname());  //设置附件路径
            fujian.setFjtype(".xlsx");
            fujianService.insertByBo(fujian);
            return fujian;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String removeLastCharacter(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return str.substring(0, str.length() - 1);
    }

    // 合并数据
    private void setMergeData(Workbook workbook, Sheet sheet, int currenRow) {
        // 移除当前行的所有现有合并区域
        removeExistingMergedRegions(sheet, currenRow);
        // 合并 B 到 F 列，合并当前行
        CellRangeAddress one = new CellRangeAddress( currenRow, currenRow,  1, 5);
        sheet.addMergedRegion(one);
        // 合并 G 到 L 列，从第 1 行到第 15 行
        CellRangeAddress two = new CellRangeAddress( currenRow, currenRow,  6, 11);
        sheet.addMergedRegion(two);
        // 合并 M 到 N 列
        CellRangeAddress three = new CellRangeAddress( currenRow, currenRow,  12, 13);
        sheet.addMergedRegion(three);
        // 合并 O 到 Q 列，从第 1 行到第 15 行
        CellRangeAddress four = new CellRangeAddress( currenRow, currenRow,  14, 16);
        sheet.addMergedRegion(four);
        // 合并 R 到 S 列
        CellRangeAddress five = new CellRangeAddress( currenRow, currenRow,  17, 18);
        sheet.addMergedRegion(five);
        // 合并 T 到 W 列
        CellRangeAddress six = new CellRangeAddress( currenRow, currenRow,  19, 22);
        sheet.addMergedRegion(six);
        // 合并 Y 到 AC 列
        CellRangeAddress seven = new CellRangeAddress( currenRow, currenRow,  24, 28);
        sheet.addMergedRegion(seven);
        // 合并 AE 到 AF 列
        CellRangeAddress eight = new CellRangeAddress( currenRow, currenRow,  30, 31);
        sheet.addMergedRegion(eight);
    }

    private void removeExistingMergedRegions(Sheet sheet, int currenRow) {
        List<CellRangeAddress> mergedRegions = sheet.getMergedRegions();
        for (int i = mergedRegions.size() - 1; i >= 0; i--) {
            CellRangeAddress region = mergedRegions.get(i);
            if (region.getFirstRow() == currenRow && region.getLastRow() == currenRow) {
                sheet.removeMergedRegion(i);
            }
        }
    }

    /**
     * 清除报价单
     * @param fjId
     * @return
     */
    @Override
    public List<ZFujianBo> clearBjd(String fjId) {
        List<ZFujianVo> zFujianList = fujianService.queryListByIdOrdery(fjId);
        List<ZFujianBo> resultFj = new ArrayList<>();
        for (ZFujianVo zFujianVo : zFujianList) {
            String fjpath = uploadPath + zFujianVo.getFjpath();
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(fjpath);
                Workbook workbook = new XSSFWorkbook(fis);
                Sheet sheet = workbook.getSheetAt(0); // 假设我们要操作第一个sheet
                int lastRowNum = sheet.getLastRowNum(); // 获取最后一行数据
                JSONArray array = new JSONArray();
                for (int i = 7; i < lastRowNum; i++) {  // 遍历当前的数据
                    JSONObject jsonObject = new JSONObject();
                    Row row = sheet.getRow(i);  // 获取当前行数据
                    // 获取列数据
                    Cell zero = row.getCell(0);
                    Cell one = row.getCell(1);
                    Cell two = row.getCell(2);
                    Cell three = row.getCell(3);
                    Cell four = row.getCell(4);
                    Cell five = row.getCell(5);
                    Cell six = row.getCell(6);
                    Cell seven = row.getCell(7);
                    Cell eight = row.getCell(8);
                    if (zero != null && StringUtils.isNotEmpty(zero.toString()) && one != null && StringUtils.isNotEmpty(one.toString())
                        && four != null && StringUtils.isNotEmpty(four.toString()) && five != null && StringUtils.isNotEmpty(five.toString())
                        && six != null && StringUtils.isNotEmpty(six.toString())
                    ) {
                        jsonObject.put("xh", (int) Double.parseDouble(zero.toString()));
                        jsonObject.put("yqmc", one.toString());
                        jsonObject.put("xhgg", two.toString());
                        jsonObject.put("glbh", three.toString());
                        // 第四列
                        double dj = 0;
                        if (four != null) {
                            dj = Double.parseDouble(four.toString());
                        }
                        jsonObject.put("dj", dj);
                        int sl = 0;
                        if (five != null) {
                            sl = (int) Double.parseDouble(five.toString());
                        }
                        jsonObject.put("sl", sl);
                        jsonObject.put("xj", dj * sl);
                        jsonObject.put("fwfs", seven.toString());
                        jsonObject.put("dqrq", eight.toString());
                        array.add(jsonObject);
                    }
                }

                String excelUrl = getTemplatePath("template/clearBjd.xlsx");
                fis = new FileInputStream(excelUrl);
                Workbook fileWorkbook = new XSSFWorkbook(fis);
                Sheet sheetOut = fileWorkbook.getSheetAt(0);
                // 遍历数据并创建行
                for (int i = 0; i < array.size(); i++) {
                    // 获取第一个数据
                    JSONObject jsonObject = array.getJSONObject(i);
                    int currenRow = i + 1;
                    Row newRow = sheetOut.createRow(currenRow);  // 在currentRow创建一行
                    newRow.setHeightInPoints(25);  // 设置行高
                    // 创建列
                    for (int j = 0; j < 13; j++) {
                        Cell cell = newRow.createCell(j);
                        setStyle(fileWorkbook, cell);
                    }
                    // 创建单元格
                    Cell xh = newRow.getCell(0);  // 序号
                    Cell yqmc = newRow.getCell(1); // 仪器名称
                    Cell xhgg = newRow.getCell(2); // 型号规格
                    Cell zzc = newRow.getCell(3);  // 制造厂商
                    Cell ccbh = newRow.getCell(4); // 出厂编号
                    Cell glbh = newRow.getCell(5); // 管理编号
                    Cell sl = newRow.getCell(6);   // 数量
                    Cell dj = newRow.getCell(7);    // 单价
                    Cell ds = newRow.getCell(8);    // 点数
                    Cell dsdj = newRow.getCell(9);  // 点数单价
                    Cell xj = newRow.getCell(10);   // 小计
                    Cell fwfs = newRow.getCell(11); // 服务方式
                    Cell bz = newRow.getCell(12);   // 备注
                    // 设置数据
                    xh.setCellValue(jsonObject.getInt("xh"));
                    yqmc.setCellValue(jsonObject.getStr("yqmc"));
                    xhgg.setCellValue(StringUtils.isNotEmpty(jsonObject.getStr("xhgg")) ? jsonObject.getStr("xhgg") : "/");
                    zzc.setCellValue("/");
                    ccbh.setCellValue("/");
                    glbh.setCellValue(StringUtils.isNotEmpty(jsonObject.getStr("glbh")) ? jsonObject.getStr("glbh") : "/");
//                    sl.setCellValue(Integer.parseInt(jsonObject.getStr("sl")));
                    sl.setCellValue(jsonObject.getInt("sl"));
//                    dj.setCellValue(Double.parseDouble(jsonObject.getStr("dj")));
                    dj.setCellValue(jsonObject.getDouble("dj"));
                    ds.setCellValue(0); dsdj.setCellValue(0);
                    xj.setCellValue(jsonObject.getDouble("xj"));
                    fwfs.setCellValue(jsonObject.getStr("fwfs"));
                    bz.setCellValue("");
                }

                // 获取当前下载excel的路径
                LocalDate currentDate = LocalDate.now();
                // 分别获取年、月、日
                int year = currentDate.getYear();
                int monthValue = currentDate.getMonthValue();
                int dayOfMonth = currentDate.getDayOfMonth();
                // 生成Excel路径
                String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/temp_qxbjd/";
                // 判断当前文件路径的文件夹是否存在，不存在则创建
                if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
                    // 路径不存在，尝试创建
                    try {
                        Files.createDirectories(Paths.get(uploadPath + suffixPath));
                    } catch (Exception e) {
                        System.err.println("创建目录时出错: " + e.getMessage());
                    }
                }
                String path = uploadPath + suffixPath + zFujianVo.getFjname();
                // 输出填充数据后的Word文档
                FileOutputStream out = new FileOutputStream(path);
                fileWorkbook.write(out);
                out.close();
                fileWorkbook.close();

                // 将当前的文件保存到附件表中
                ZFujianBo fujian = new ZFujianBo();
                fujian.setFjid(IdUtil.simpleUUID());  //设置附件id
                fujian.setFjname(zFujianVo.getFjname());   //设置附件名称
                fujian.setFjpath(suffixPath + zFujianVo.getFjname());  //设置附件路径
                fujian.setFjtype(".xlsx");
                fujianService.insertByBo(fujian);
                resultFj.add(fujian);

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (URISyntaxException e) {
                throw new RuntimeException(e);
            }
        }
        return resultFj;
    }

    @Override
    public int updateShByKhId(String id, String sh) {
        return baseMapper.updateShByKhId(id, sh);
    }

    /**
     * 开发票
     * @param list
     * @return
     */
    @Override
    public byte[] handleKfp(List<ZYwdwgdKfpVo> list) {
        if (list.size() > 0) {
            // 保存工作簿
            FileOutputStream fos = null;
            try {
                // 创建一个新的工作簿
                Workbook workbook = new XSSFWorkbook();
                // 创建一个新的工作表
                Sheet sheet = workbook.createSheet("发票");
                int index = 1;
                int index2 = 1;
                // 创建表头
                Row r = sheet.createRow(1);
                r.createCell(0).setCellValue("序号"); r.createCell(1).setCellValue("完工编号");
                r.createCell(2).setCellValue("公司名称"); r.createCell(3).setCellValue("税号");
                r.createCell(4).setCellValue("开票金额"); r.createCell(5).setCellValue("开票地址 电话");
                r.createCell(6).setCellValue("开户行 账号"); r.createCell(7).setCellValue("开票日期");
                r.createCell(8).setCellValue("开票时间"); r.createCell(9).setCellValue("备注");
                // 创建一些数据
                for (int i = 0; i < list.size(); i++) {
                    ZYwdwgdKfpVo zYwdwgdKfpVo = list.get(i);
                    Field[] fields = zYwdwgdKfpVo.getClass().getDeclaredFields();
                    // 创建一行数据
                    Row row = sheet.createRow(i+2);
                    for (int j = 0; j < fields.length; j++){
                        Field field = fields[j];
                        // 设置访问权限（即使字段是私有的）
                        field.setAccessible(true);
                        // 获取字段名称
                        String fieldName = field.getName();
                        Object fieldValue = null;
                        // 获取字段值
                        try {
                            fieldValue = field.get(zYwdwgdKfpVo);
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                        // 创建单元格
                        Cell cell = row.createCell(j);
                        if (fieldName.equals("kprq")) {
                            index = j;
                            if (fieldValue != null) {
                                cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(fieldValue));
                            }else {
                                cell.setCellValue("");
                            }
                        }else if (fieldName.equals("xzkpsj")) {
                            index2 = j;
                            if (fieldValue != null) {
                                cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fieldValue));
                            }else {
                                cell.setCellValue("");
                            }
                        }else {
                            if (fieldValue != null) {
                                cell.setCellValue(fieldValue.toString());
                            }else {
                                cell.setCellValue("");
                            }
                        }
                    }
                }
                // 设置宽度
                sheet.setColumnWidth(1, 15 * 256);
                sheet.setColumnWidth(2, 25 * 256);
                sheet.setColumnWidth(3, 20 * 256);
                sheet.setColumnWidth(4, 10 * 256);
                sheet.setColumnWidth(5, 40 * 256);
                sheet.setColumnWidth(6, 30 * 256);
                sheet.setColumnWidth(7, 20 * 256);
                sheet.setColumnWidth(8, 20 * 256);
                sheet.setColumnWidth(9, 40 * 256);

                int lastRowNum = sheet.getLastRowNum();

                // 分别获取年、月、日
                LocalDateTime currentDateTime = LocalDateTime.now();
                int year = currentDateTime.getYear();
                int monthValue = currentDateTime.getMonthValue();
                int dayOfMonth = currentDateTime.getDayOfMonth();
                int hour = currentDateTime.getHour();
                int minute = currentDateTime.getMinute();
                int second = currentDateTime.getSecond();
                String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/";
                // 判断当前文件路径的文件夹是否存在，不存在则创建
                if (!Files.exists(Paths.get(kfpPath + suffixPath))) {
                    // 路径不存在，尝试创建
                    try {
                        Files.createDirectories(Paths.get(kfpPath + suffixPath));
                    } catch (Exception e) {
                        System.err.println("创建目录时出错: " + e.getMessage());
                    }
                }
                // 生成防伪秘钥
                ZYwdwgdKfpVo zYwdwgdKfpVo = list.get(0);
                String key = zYwdwgdKfpVo.getWgbh() + "_" + year + monthValue + dayOfMonth + "" + hour + minute + second;
                String yzmPath = kfpPath + suffixPath + "" +year + monthValue + dayOfMonth + "" + hour + minute + second + ".png";
                int width = 200; // 二维码宽度
                int height = 200; // 二维码高度

                // 创建一个单元格样式
                CellStyle style = workbook.createCellStyle();
                style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
                style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
                // 创建一个字体样式
                Font font = workbook.createFont();
                font.setFontHeightInPoints((short) 25); // 设置字体大小为20px
                style.setFont(font);

                // 设置秘钥
                Row r2 = sheet.createRow(0);
                Cell cell1 = r2.createCell(0);
                r2.createCell(1).setCellStyle(style);r2.createCell(2).setCellStyle(style);r2.createCell(3).setCellStyle(style);
                r2.createCell(4).setCellStyle(style);r2.createCell(5).setCellStyle(style);r2.createCell(6).setCellStyle(style);
                r2.createCell(7).setCellStyle(style);r2.createCell(8).setCellStyle(style);r2.createCell(9).setCellStyle(style);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 9)); // 合并单元格
                cell1.setCellValue(key);
                cell1.setCellStyle(style);
                r2.setRowStyle(style);

                // 设置二维码参数
                Map<EncodeHintType, Object> hints = new HashMap<>();
                hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.name());
                hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

                // 创建二维码写入对象
                QRCodeWriter qrCodeWriter = new QRCodeWriter();
                BitMatrix bitMatrix = qrCodeWriter.encode(key, BarcodeFormat.QR_CODE, width, height, hints);

                // 将二维码保存为图片文件
                Path path = FileSystems.getDefault().getPath(yzmPath);
                MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

                FileInputStream fis = new FileInputStream(path.toFile());
                byte[] b = IOUtils.toByteArray(fis);
                int pictureIdx = workbook.addPicture(b, Workbook.PICTURE_TYPE_PNG);
                fis.close();
                // 创建一个画布
                CreationHelper helper = workbook.getCreationHelper();
                Drawing<?> drawing = sheet.createDrawingPatriarch();
                // 定义图片的位置和大小
                ClientAnchor anchor = helper.createClientAnchor();
                anchor.setCol1(0); // 图片左上角所在的列
                anchor.setRow1(lastRowNum + 3); // 图片左上角所在的行
                anchor.setCol2(1); // 图片右下角所在的列
                anchor.setRow2(lastRowNum + 4); // 图片右下角所在的行
                // 插入图片
                Picture pict = drawing.createPicture(anchor, pictureIdx);
                // 调整图片大小
                pict.resize();

                // 锁定所有单元格
                CellStyle lockedCellStyle = workbook.createCellStyle();
                lockedCellStyle.setLocked(true);
                // 解锁特定列的单元格
                CellStyle unlockedCellStyle = workbook.createCellStyle();
                unlockedCellStyle.setLocked(false);
                // 遍历所有行，设置特定列的单元格样式
                for (Row row : sheet) {
                    for (Cell cell : row) {
                        if (cell.getColumnIndex() == 9) {
                            cell.setCellStyle(unlockedCellStyle);
                        }else {
                            cell.setCellStyle(lockedCellStyle);
                        }
                    }
                }
                // 设置第一行锁定
                cell1.setCellStyle(lockedCellStyle);
                // 保护工作表
                sheet.protectSheet("dfkfp");

                // excel 文件名
                String excelFileName = year + monthValue + dayOfMonth + "" + hour + minute + second + ".xlsx";
                fos = new FileOutputStream(kfpPath + suffixPath + excelFileName);
                workbook.write(fos);
                fos.close();
                workbook.close();
                // 获取当前的文件流
                FileInputStream inputStream = new FileInputStream(kfpPath + suffixPath + excelFileName);
                byte[] bytes = IOUtils.toByteArray(inputStream);
                inputStream.close();
                return bytes;

            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (WriterException e) {
                throw new RuntimeException(e);
            }
        }else {
            return null;
        }

    }

    /**
     * 记录日志
     */
    public void handleLog(int type, ZYwdwgd add, ZYwdwgd update) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (type == 0) {  // 当前是新增数据
            ZYwdwgdLog zYwdwgdLog = new ZYwdwgdLog();
            zYwdwgdLog.setType("add");
            zYwdwgdLog.setCreateId(loginUser.getUserId() + "");
            zYwdwgdLog.setCreateBy(loginUser.getNickName());
            zYwdwgdLog.setCreateTime(new Date());
            // 将数据转换为历史数据
//                ZYwdwgdHistory history = transverterBean(add);
            ZYwdwgdHistory history = BeanUtil.toBean(add, ZYwdwgdHistory.class);
            history.setHistoryid(IdUtil.simpleUUID());
            Boolean b = zyhHistoryService.insert(history);
            if (b) {
                // 构建日志消息
                StringBuffer sb = new StringBuffer();
                sb.append(loginUser.getNickName() + "新增了一条数据。");
                if (StringUtils.isNotEmpty(history.getBjdh())) {
                    sb.append("报价单号为：" + history.getBjdh());
                }
                if (StringUtils.isNotEmpty(history.getWgdh())) {
                    sb.append("完工单号为：" + history.getWgdh());
                }
                zYwdwgdLog.setMsg(sb.toString());
                // 将数据存入历史数据中
                zYwdwgdLog.setFont(history.getHistoryid());
            }else {
                zYwdwgdLog.setMsg("历史数据记录失败！请联系管理员处理。");
            }
            zywgdLogService.insert(zYwdwgdLog);

        }else if(type == 1 || type == 2) {  //当前是修改数据
            ZYwdwgdLog zYwdwgdLog = new ZYwdwgdLog();
            if (type == 1) {
                zYwdwgdLog.setType("update");
            }else if (type == 2) {
                zYwdwgdLog.setType("xcap");
            }
            zYwdwgdLog.setCreateId(loginUser.getUserId() + "");
            zYwdwgdLog.setCreateBy(loginUser.getNickName());
            zYwdwgdLog.setCreateTime(new Date());
            // 将数据转换为历史数据
            ZYwdwgdHistory history = BeanUtil.toBean(add, ZYwdwgdHistory.class);
            history.setHistoryid(IdUtil.simpleUUID());
            Boolean a = zyhHistoryService.insert(history);
            // 将修改的数据添加历史数据
            ZYwdwgdHistory history2 = BeanUtil.toBean(update, ZYwdwgdHistory.class);
            history2.setHistoryid(IdUtil.simpleUUID());
            Boolean b = zyhHistoryService.insert(history2);
            if (a && b && type == 1) {
                // 构建日志消息
                StringBuffer sb = new StringBuffer();
                sb.append(loginUser.getNickName() + "修改了一条数据。");
                if (StringUtils.isNotEmpty(history2.getBjdh())) {
                    sb.append("报价单号为：" + history2.getBjdh());
                }
                if (StringUtils.isNotEmpty(history2.getWgdh())) {
                    sb.append("完工单号为：" + history2.getWgdh());
                }
                zYwdwgdLog.setMsg(sb.toString());
            }else if (a && b && type == 2) {
                // 构建日志消息
                StringBuffer sb = new StringBuffer();
                sb.append(loginUser.getNickName()
                    + "安排下场负责人：" + history2.getXcfzrname()
                    + " 安排下场人员：" + history2.getXcryname()
                );
                if (StringUtils.isNotEmpty(history2.getBjdh())) {
                    sb.append("报价单号为：" + history2.getBjdh());
                }
                if (StringUtils.isNotEmpty(history2.getWgdh())) {
                    sb.append("完工单号为：" + history2.getWgdh());
                }
                zYwdwgdLog.setMsg(sb.toString());
            }else {
                zYwdwgdLog.setMsg("历史数据记录失败！请联系管理员处理。");
            }
            // 将数据存入历史数据中
            zYwdwgdLog.setFont(history.getHistoryid());
            zYwdwgdLog.setLater(history2.getHistoryid());
            zywgdLogService.insert(zYwdwgdLog);
        }
    }

    // 定义转换器
    private ZYwdwgdHistory transverterBean(ZYwdwgd add) throws IllegalAccessException {
        ZYwdwgdHistory target = new ZYwdwgdHistory();
        // 获取源对象的所有字段
        Field[] sourceFields = add.getClass().getDeclaredFields();
        for (Field sourceField : sourceFields) {
            sourceField.setAccessible(true); // 设置字段可访问
            // 获取目标对象中同名字段
            Field targetField;
            try {
                targetField = target.getClass().getDeclaredField(sourceField.getName());
            } catch (NoSuchFieldException e) {
                // 如果目标对象中没有找到同名字段，则跳过
                continue;
            }
            targetField.setAccessible(true); // 设置字段可访问
            // 将源对象字段的值赋给目标对象字段
            targetField.set(target, sourceField.get(add));
        }
        return target;
    }

}
